package com.ssy.lingxi.product.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.member.RoleTypeEnum;
import com.ssy.lingxi.common.constant.product.*;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.MemberAndRoleIdDTO;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.logistics.api.dto.request.LogisticsMemberIdAndRoleIdReq;
import com.ssy.lingxi.logistics.api.dto.request.LogisticsSelectCompanyListFeignReq;
import com.ssy.lingxi.logistics.api.dto.response.CommonSelectResponse;
import com.ssy.lingxi.logistics.api.dto.response.FreightTemplateFeignRes;
import com.ssy.lingxi.logistics.api.dto.response.ShipperAddressSelectFeignRes;
import com.ssy.lingxi.logistics.api.enums.CooperateTypeEnum;
import com.ssy.lingxi.logistics.api.feign.LogisticsSelectControllerFeign;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberInnerControllerFeign;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberLevelRightCreditControllerFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignLevelDetailVO;
import com.ssy.lingxi.message.api.constant.MessageTemplateCode;
import com.ssy.lingxi.message.api.feign.SystemMessageControllerFeign;
import com.ssy.lingxi.message.api.vo.request.SystemMessageRequest;
import com.ssy.lingxi.platform.manage.api.feign.inner.MaterialLibraryFeignController;
import com.ssy.lingxi.platform.manage.api.feign.inner.ShopRuleActivityFeign;
import com.ssy.lingxi.platform.manage.api.model.dto.material.MaterialFileInfoDTO;
import com.ssy.lingxi.platform.manage.api.model.dto.shop.ShopMemberInfoDTO;
import com.ssy.lingxi.platform.manage.api.model.vo.material.MaterialFileFeignVO;
import com.ssy.lingxi.platform.template.api.feign.inner.PageTemplateWebControllerFeign;
import com.ssy.lingxi.platform.template.api.model.dto.inner.OpenMroInnerDTO;
import com.ssy.lingxi.product.api.model.request.CommodityDraftRequest;
import com.ssy.lingxi.product.api.model.request.SimpleIdListRequest;
import com.ssy.lingxi.product.api.model.request.SimpleIdRequest;
import com.ssy.lingxi.product.api.model.request.commodity.*;
import com.ssy.lingxi.product.api.model.request.feign.CommodityNameRequest;
import com.ssy.lingxi.product.api.model.request.feign.CommodityPriceRequest;
import com.ssy.lingxi.product.api.model.response.*;
import com.ssy.lingxi.product.api.model.response.commodity.*;
import com.ssy.lingxi.product.api.model.response.feign.CommodityPriceResponse;
import com.ssy.lingxi.product.api.model.response.feign.CommoditySkuStockResponse;
import com.ssy.lingxi.product.common.CodeUtils;
import com.ssy.lingxi.product.common.enums.*;
import com.ssy.lingxi.product.entity.*;
import com.ssy.lingxi.product.entity.commodity.*;
import com.ssy.lingxi.product.entity.commodity.member.CommodityMember;
import com.ssy.lingxi.product.entity.commodity.member.CommodityMemberLevel;
import com.ssy.lingxi.product.entity.commodity.member.CommodityMemberUnitPrice;
import com.ssy.lingxi.product.entity.commodity.member.CommodityUnitPriceStrategy;
import com.ssy.lingxi.product.entity.customer.CustomerAttribute;
import com.ssy.lingxi.product.entity.customer.CustomerAttributeValue;
import com.ssy.lingxi.product.entity.customer.CustomerCategory;
import com.ssy.lingxi.product.entity.platform.Category;
import com.ssy.lingxi.product.model.CommodityImport;
import com.ssy.lingxi.product.repository.*;
import com.ssy.lingxi.product.repository.commodity.*;
import com.ssy.lingxi.product.repository.customer.CustomerAttributeRepository;
import com.ssy.lingxi.product.repository.customer.CustomerAttributeValueRepository;
import com.ssy.lingxi.product.repository.customer.CustomerCategoryRepository;
import com.ssy.lingxi.product.service.ICommodityService;
import com.ssy.lingxi.product.service.es.ISyncEsCommodityService;
import com.ssy.lingxi.product.utils.ExcelReactData;
import com.ssy.lingxi.product.utils.ExcelUtil;
import com.ssy.lingxi.report.api.enums.CommodityOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.OperateDataSourceEnum;
import com.ssy.lingxi.report.api.feign.ReportControllerFeign;
import com.ssy.lingxi.report.api.vo.request.OperateNoticeVO;
import jodd.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品实现类
 *
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/6/22
 */
@Service
public class CommodityServiceImpl implements ICommodityService {

    @Resource
    private CommodityRepository commodityRepository;

    @Resource
    private GoodsRepository goodsRepository;

    @Resource
    private CustomerAttributeRepository customerAttributeRepository;

    @Resource
    private CustomerAttributeValueRepository customerAttributeValueRepository;

    @Resource
    private CommodityCheckRecordRepository commodityCheckRecordRepository;

    @Resource
    private CommodityShopRepository commodityShopRepository;

    @Resource
    private CustomerCategoryRepository customerCategoryRepository;

    @Resource
    private BrandRepository brandRepository;

    @Resource
    private CommodityUnitPriceAndPicRepository commodityUnitPriceAndPicRepository;

    @Resource
    private CommodityAttributeRepository commodityAttributeRepository;

    @Resource
    private CommodityGoodsAttributeRepository commodityGoodsAttributeRepository;

    @Resource
    private CommodityAreaRepository commodityAreaRepository;

    @Resource
    private CommodityRemarkRepository commodityRemarkRepository;

    @Resource
    private CommodityUnitPriceStrategyRepository commodityUnitPriceStrategyRepository;

    @Resource
    private CommodityMemberUnitPriceRepository commodityMemberUnitPriceRepository;

    @Resource
    private CommodityMemberRepository commodityMemberRepository;

    @Resource
    private CommodityMemberLevelRepository commodityMemberLevelRepository;

    @Resource
    private OftenBuyCommodityRepository oftenBuyCommodityRepository;

    @Resource
    private CommodityPriceRecordRepository priceRecordRepository;

    @Resource
    private ISyncEsCommodityService syncEsCommodityService;

    @Resource
    private ReportControllerFeign reportControllerFeign;

    @Resource
    private IRedisStringUtils redisStringUtils;

    @Resource
    private SystemMessageControllerFeign systemMessageControllerFeign;

    @Resource
    private ShopRuleActivityFeign shopRuleActivityFeign;

    @Resource
    private PageTemplateWebControllerFeign pageTemplateWebControllerFeign;

    @Resource
    private MemberInnerControllerFeign memberInnerControllerFeign;

    @Resource
    private CommodityDraftRepository commodityDraftRepository;

    @Resource
    private LogisticsSelectControllerFeign logisticsSelectControllerFeign;

    @Resource
    private MaterialLibraryFeignController materialLibraryFeignController;

    @Resource
    private MemberLevelRightCreditControllerFeign memberLevelRightCreditControllerFeign;

    /**
     * 查询商品列表 -- 商品能力
     *
     * @param pageVO
     * @param commodityQueryRequest
     * @return Page<Attribute>
     */
    @Override
    public Page<Commodity> getCommodityList(PageVO pageVO, CommodityQueryRequest commodityQueryRequest) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return commodityRepository.findAll(getSpecification(commodityQueryRequest), page);
    }

    /**
     * 查询商品
     *
     * @param id
     * @return Commodity
     */
    @Override
    public Commodity getCommodity(Long id) {
        return commodityRepository.findById(id).orElse(null);
    }

    /**
     * 添加/修改商品
     *
     * @param sysUser
     * @param commodityRequest
     * @return
     */
    @Transactional
    @Override
    public Long saveOrUpdateCommodity(UserLoginCacheDTO sysUser, CommodityAddRequest commodityRequest) {
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        Long id = commodityRequest.getId();
        String name = commodityRequest.getName();
        Boolean isUpdateAttribute = commodityRequest.getIsUpdateAttribute();
        //是否为S2B获取商品 , S2B商品不能修改品类、品牌、属性、属性值
        boolean isUpdateS2BDate = Objects.isNull(commodityRequest.getSourceType());
        Commodity commodity;
        List<Commodity> commodityList;
        //商品状态，用于首页数据的更新
        Integer currentStatus = 0;
        //通过id判断是新增还是修改
        if (id != null && id > 0) {
            //验证数据库中是否存在该数据
            commodity = commodityRepository.findById(id).orElse(null);
            if (commodity == null) {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
            }
            //商品状态为待审核或已上架不能修改
            if (CommodityStatusEnum.Not_Check.getCode().equals(commodity.getStatus()) || CommodityStatusEnum.On_Shelf.getCode().equals(commodity.getStatus())) {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_STATUS_NOT_UPDATE);
            }
            //记录修改前的商品状态
            currentStatus = commodity.getStatus();
            commodityList = commodityRepository.findByMemberIdAndMemberRoleIdAndNameAndIdNot(memberId, memberRoleId, name, id);
            //清除中间表数据
            this.clearMiddleTable(commodity, isUpdateAttribute, isUpdateS2BDate);
            //清除主图，重新生成
            commodity.setMainPic(null);
        } else {
            commodity = new Commodity();
//            commodity.setType(CommodityTypeEnum.Self.getCode());
            commodityList = commodityRepository.findByMemberIdAndMemberRoleIdAndName(memberId, memberRoleId, name);
        }
        //判断商品名称是否重复
        if (!commodityList.isEmpty()) {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NAME_EXIST);
        }

        //商品类型为上游供应商品时 , 定价方式不能为积分兑换
        if (CommodityS2BTypeEnum.UPPER_SUPPLY_COMMODITY.getCode().equals(commodityRequest.getType()) &&
                PriceTypeEnum.Score.getCode().equals(commodityRequest.getPriceType())) {
            throw new BusinessException(ResponseCode.PRICE_TYPE_ERROR);
        }

        String[] ignoreProperties = new String[]{"commodityAttributeList", "unitPriceAndPicList", "commodityRemark"};
        BeanUtil.copyProperties(commodityRequest, commodity, ignoreProperties);
        commodity.setType(commodityRequest.getType());
//        BeanUtil.copyProperties(commodityRequest, commodity);

        //区域
        List<CommodityArea> commodityAreaList = commodity.getCommodityAreaList();
        if (commodityAreaList != null && !commodityAreaList.isEmpty()) {
            commodity.getCommodityAreaList().stream().filter(Objects::nonNull).forEach(commodityArea -> commodityArea.setCommodity(commodity));
        }

        //判断品类是否存在
        Long categoryId = commodityRequest.getCustomerCategoryId();
        if (categoryId != null && categoryId > 0 && isUpdateS2BDate) {
            CustomerCategory customerCategory = customerCategoryRepository.findById(categoryId).orElse(null);
            if (customerCategory == null) {
                throw new BusinessException(ResponseCode.PRODUCT_CATEGORY_NOT_EXIST);
            }
            commodity.setCustomerCategory(customerCategory);
        } else if (isUpdateS2BDate) {
            throw new BusinessException(ResponseCode.PRODUCT_CATEGORY_NOT_EXIST);
        }

        //判断品牌是否存在
        Long brandId = commodityRequest.getBrandId();
        if (brandId != null && brandId > 0 && isUpdateS2BDate) {
            Brand brand = brandRepository.findById(brandId).orElse(null);
            if (brand == null) {
                throw new BusinessException(ResponseCode.PRODUCT_BRAND_NOT_EXIST);
            }
            //判断是否审核通过
            Integer brandStatus = brand.getStatus();
            if (!CommodityStatusEnum.Pass.getCode().equals(brandStatus)) {
                throw new BusinessException(ResponseCode.PRODUCT_BRAND_NOT_PASS);
            }
            //判断是否启用
            Boolean isEnable = brand.getIsEnable();
            if (!isEnable) {
                throw new BusinessException(ResponseCode.PRODUCT_BRAND_NOT_ENABLE);
            }
            commodity.setBrand(brand);
        }

        //属性校验
        List<CommodityAttribute> commodityAttributeList = new ArrayList<>();
        List<CommodityAttributeRequest> attributeRequestList = commodityRequest.getCommodityAttributeList();
        if (attributeRequestList != null && isUpdateS2BDate) {
            //判断属性是否存在
            attributeRequestList.forEach(customerAttributeRequest -> {
                CommodityAttribute commodityAttribute = new CommodityAttribute();
                //判断所有会员属性是否存在
                Long customerAttributeId = customerAttributeRequest.getCustomerAttribute().getId();
                CustomerAttribute customerAttribute = customerAttributeRepository.findById(customerAttributeId).orElse(null);
                if (customerAttribute != null) {
                    Boolean isEnable = customerAttribute.getIsEnable();
                    if (isEnable) {
                        commodityAttribute.setCustomerAttribute(customerAttribute);
                    } else {
                        throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_NOT_ENABLE);
                    }
                } else {
                    throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_NOT_EXIST);
                }
                //判断所有会员属性值是否存在
                List<CustomerAttributeValue> customerAttributeValueList = new ArrayList<>();
                customerAttributeRequest.getCustomerAttributeValueList().forEach(customerAttributeValueRequest -> {
                    Long customerAttributeValueId = customerAttributeValueRequest.getId();

                    if (customerAttributeValueId != null && customerAttributeValueId > 0) {
                        CustomerAttributeValue customerAttributeValue = customerAttributeValueRepository.findById(customerAttributeValueId).orElse(null);
                        if (customerAttributeValue != null) {
                            Boolean isEnable = customerAttributeValue.getIsEnable();
                            if (isEnable) {
                                customerAttributeValueList.add(customerAttributeValue);
                            } else {
                                throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_VALUE_NOT_ENABLE);
                            }
                        } else {
                            throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_VALUE_NOT_EXIST);
                        }
                    } else {
                        String value = customerAttributeValueRequest.getValue();
                        CustomerAttributeValue customerAttributeValue = customerAttributeValueRepository.findFirstByMemberIdAndMemberRoleIdAndValue(sysUser.getMemberId(), sysUser.getMemberRoleId(), value);
                        customerAttributeValueList.add(customerAttributeValue);
                    }
                });
                commodityAttribute.setCustomerAttributeValueList(customerAttributeValueList);
                commodityAttribute.setCommodity(commodity);
                commodityAttributeList.add(commodityAttribute);
            });
            commodity.setCommodityAttributeList(commodityAttributeList);
        } else if (isUpdateS2BDate) {
            throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_NOT_EXIST);
        }

        //转换单价和图片
        List<CommodityUnitPriceAndPic> unitPriceAndPicList = new ArrayList<>();
        commodityRequest.getUnitPriceAndPicList().forEach(unitPriceAndPicRequest -> {
            //取第一张为主图
            String mainPic = commodity.getMainPic();
            if (StringUtils.isEmpty(mainPic)) {
                String[] commodityPic = unitPriceAndPicRequest.getCommodityPic();
                if (commodityPic != null && commodityPic.length > 0) {
                    commodity.setMainPic(commodityPic[0]);
                }
            }
            CommodityUnitPriceAndPic commodityUnitPriceAndPic = new CommodityUnitPriceAndPic();
            if (isUpdateAttribute != null && !isUpdateAttribute) {
                Long unitPriceAndPicId = unitPriceAndPicRequest.getId();
                if (unitPriceAndPicId != null && unitPriceAndPicId > 0) {
                    commodityUnitPriceAndPic = commodityUnitPriceAndPicRepository.findById(unitPriceAndPicId).orElse(null);
                    if (commodityUnitPriceAndPic == null) {
                        throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_UNITPRICE_NOT_EXIST);
                    }
                }
            }
            //检查货品
            SimpleIdRequest goodsRequest = unitPriceAndPicRequest.getGoods();
            if (goodsRequest != null) {
                Long goodsId = goodsRequest.getId();
                if (goodsId != null && goodsId > 0) {
                    Goods goods = goodsRepository.findById(goodsId).orElse(null);
                    if (goods != null) {
                        commodityUnitPriceAndPic.setGoods(goods);
                    } else {
                        throw new BusinessException(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
                    }
                }
            }

            //判断是否阶梯价格
            Map<String, Double> unitPrice = unitPriceAndPicRequest.getUnitPrice();
            if (unitPrice != null) {
                boolean flag = unitPrice.keySet().stream().anyMatch(s -> s.equals("0-0"));
                commodityUnitPriceAndPic.setIsMorePrice(!flag);
            }

            List<CommodityGoodsAttribute> attributeAndValueList = new ArrayList<>();
            CommodityUnitPriceAndPic finalCommodityUnitPriceAndPic = commodityUnitPriceAndPic;
            unitPriceAndPicRequest.getAttributeAndValueList().forEach(attributeRequest -> {
                CommodityGoodsAttribute commodityGoodsAttribute = new CommodityGoodsAttribute();
                //根据配置检查属性和属性值
                Long customerAttributeId = attributeRequest.getCustomerAttribute().getId();
                if (customerAttributeId != null && customerAttributeId > 0) {
                    CustomerAttribute customerAttribute = customerAttributeRepository.findById(customerAttributeId).orElse(null);
                    if (customerAttribute != null) {
                        Boolean isEnable = customerAttribute.getIsEnable();
                        if (isEnable) {
                            commodityGoodsAttribute.setCustomerAttribute(customerAttribute);
                        } else {
                            throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_NOT_ENABLE);
                        }
                    } else {
                        throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_NOT_EXIST);
                    }
                } else {
                    throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_NOT_EXIST);
                }
                Long customerAttributeValueId = attributeRequest.getCustomerAttributeValue().getId();
                if (customerAttributeValueId != null && customerAttributeValueId > 0) {
                    CustomerAttributeValue customerAttributeValue = customerAttributeValueRepository.findById(customerAttributeValueId).orElse(null);
                    if (customerAttributeValue != null) {
                        Boolean isEnable = customerAttributeValue.getIsEnable();
                        if (isEnable) {
                            commodityGoodsAttribute.setCustomerAttributeValue(customerAttributeValue);
                        } else {
                            throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_VALUE_NOT_ENABLE);
                        }
                    } else {
                        throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_VALUE_NOT_EXIST);
                    }
                } else {
                    String value = attributeRequest.getCustomerAttributeValue().getValue();
                    CustomerAttributeValue customerAttributeValue = customerAttributeValueRepository.findFirstByMemberIdAndMemberRoleIdAndValue(sysUser.getMemberId(), sysUser.getMemberRoleId(), value);
                    commodityGoodsAttribute.setCustomerAttributeValue(customerAttributeValue);
                }
                commodityGoodsAttribute.setCommodityUnitPriceAndPic(finalCommodityUnitPriceAndPic);
                attributeAndValueList.add(commodityGoodsAttribute);
            });
            commodityUnitPriceAndPic.setAttributeAndValueList(attributeAndValueList);
            commodityUnitPriceAndPic.setUnitPrice(unitPriceAndPicRequest.getUnitPrice());
            commodityUnitPriceAndPic.setCommodityPic(unitPriceAndPicRequest.getCommodityPic());
            commodityUnitPriceAndPic.setPriceRate(unitPriceAndPicRequest.getPriceRate());
            commodityUnitPriceAndPic.setHsCode(unitPriceAndPicRequest.getHsCode());
            commodityUnitPriceAndPic.setCommodity(commodity);
            unitPriceAndPicList.add(commodityUnitPriceAndPic);
        });
        commodity.setUnitPriceAndPicList(unitPriceAndPicList);

        //判断商品图片是否为空
        String mainPic = commodity.getMainPic();
        if (StringUtil.isEmpty(mainPic)) {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_IMAGE_NOT_NULL);
        }

        //计算最大值和最小值
        List<Map<String, Double>> collect = commodityRequest.getUnitPriceAndPicList().stream().filter(unitPriceAndPic -> unitPriceAndPic != null && unitPriceAndPic.getUnitPrice() != null && unitPriceAndPic.getUnitPrice().size() > 0).map(UnitPriceAndPicRequest::getUnitPrice).collect(Collectors.toList());
        if (!collect.isEmpty()) {
            Double min = Collections.min(collect.stream().map(m -> Collections.min(m.values())).collect(Collectors.toList()));
            Double max = Collections.max(collect.stream().map(m -> Collections.max(m.values())).collect(Collectors.toList()));
            commodity.setMin(min);
            commodity.setMax(max);
        } else {
            commodity.setMin(0d);
            commodity.setMax(0d);
        }

        //商品描述
        CommodityRemarkRequest commodityRemarkRequest = commodityRequest.getCommodityRemark();
        if (commodityRemarkRequest != null) {
            CommodityRemark commodityRemark = new CommodityRemark();
            commodityRemark.setWord(commodityRemarkRequest.getWord());
            commodityRemark.setVideo(commodityRemarkRequest.getVideo());
            List<CommodityRemarkImageRequest> imageList = commodityRemarkRequest.getImageList();
            if (imageList != null && imageList.size() > 0) {
                List<CommodityRemarkImage> commodityRemarkImageList = imageList.stream().filter(Objects::nonNull).map(commodityRemarkImageRequest -> {
                    CommodityRemarkImage commodityRemarkImage = new CommodityRemarkImage();
                    commodityRemarkImage.setCommodityRemark(commodityRemark);
                    commodityRemarkImage.setUrl(commodityRemarkImageRequest.getUrl());
                    commodityRemarkImage.setLinkType(commodityRemarkImageRequest.getLinkType());
                    commodityRemarkImage.setImageType(commodityRemarkImageRequest.getImageType());
                    return commodityRemarkImage;
                }).collect(Collectors.toList());
                commodityRemark.setImageList(commodityRemarkImageList);
            }
            commodity.setCommodityRemark(commodityRemark);
        }

        //获取会员信息
        commodity.setMemberId(sysUser.getMemberId());
        commodity.setMemberName(sysUser.getCompany());
        commodity.setMemberRoleId(sysUser.getMemberRoleId());
        commodity.setMemberRoleName(sysUser.getMemberRoleName());
        commodity.setUserId(sysUser.getUserId());
        commodity.setUserName(sysUser.getUserName());
        commodity.setStatus(CommodityStatusEnum.Not_Submitted.getCode());

        //判断是平台审核还是会员审核
        //调用平台管理服务->判断当前会员是否有自营商城
        ShopMemberInfoDTO dto = new ShopMemberInfoDTO();
        dto.setMemberId(sysUser.getMemberId());
        dto.setMemberRoleId(sysUser.getMemberRoleId());
        Wrapper<Boolean> existShop = shopRuleActivityFeign.existShop(dto);
        Boolean result = existShop.getData();
        if (!result) {
            commodity.setCheckType(CheckTypeEnum.PLATFORM_CHECK.getCode());//平台审核
        }

        //数据库持久化对象
        commodityRepository.saveAndFlush(commodity);

        //新增的时候才需要更新code
        if (id == null || id <= 0) {
            //根据id转成6位32进制字符
            String code = CodeUtils.digits32(commodity.getId(), Constants.CODE_NUM);
            commodity.setCode(Constants.COMMODITY_CODE_PREFIX + code);
            //数据库持久化对象
            commodityRepository.saveAndFlush(commodity);

            //首页数据统计
            try {
                List<OperateNoticeVO> operateNoticeVOList = new ArrayList<>();
                //商品总数
                OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                operateNoticeVO.setMemberId(commodity.getMemberId());
                operateNoticeVO.setRoleId(commodity.getMemberRoleId());
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.PRODUCT_COUNT.getCode());
                operateNoticeVO.setIncreaseCount(1L);
                operateNoticeVOList.add(operateNoticeVO);
                //待提交审核商品
                operateNoticeVO = new OperateNoticeVO();
                operateNoticeVO.setMemberId(commodity.getMemberId());
                operateNoticeVO.setRoleId(commodity.getMemberRoleId());
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_VALIFY_COMMIT.getCode());
                operateNoticeVO.setIncreaseCount(1L);
                operateNoticeVOList.add(operateNoticeVO);
                reportControllerFeign.addOperateNoticeList(operateNoticeVOList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                //同步交易规则中的商品信息？

                if (!CommodityStatusEnum.Not_Submitted.getCode().equals(currentStatus) && !CommodityStatusEnum.Not_Pass.getCode().equals(currentStatus)) {
                    //修改后待提交审核+1
                    List<OperateNoticeVO> operateNoticeVOList = new ArrayList<>();
                    OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                    operateNoticeVO.setMemberId(commodity.getMemberId());
                    operateNoticeVO.setRoleId(commodity.getMemberRoleId());
                    operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                    operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_VALIFY_COMMIT.getCode());
                    operateNoticeVO.setIncreaseCount(1L);
                    operateNoticeVOList.add(operateNoticeVO);
                    //已下架或者未上架状态下修改，待上架商品-1
                    if (CommodityStatusEnum.Off_Shelf.getCode().equals(currentStatus) || CommodityStatusEnum.NEVER_Shelf.getCode().equals(currentStatus)) {
                        operateNoticeVO = new OperateNoticeVO();
                        operateNoticeVO.setMemberId(commodity.getMemberId());
                        operateNoticeVO.setRoleId(commodity.getMemberRoleId());
                        operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                        operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_PUBLISH.getCode());
                        operateNoticeVO.setReduceCount(1L);
                        operateNoticeVOList.add(operateNoticeVO);
                    }
                    reportControllerFeign.addOperateNoticeList(operateNoticeVOList);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return commodity.getId();
    }

    /**
     * 清除中间表
     *
     * @param commodity
     * @param isUpdateAttribute
     * @param isUpdateS2BDate
     */
    private void clearMiddleTable(Commodity commodity, Boolean isUpdateAttribute, Boolean isUpdateS2BDate) {
        //清除商品地市中间表
        List<CommodityArea> currentCommodityAreaList = commodity.getCommodityAreaList();
        if (currentCommodityAreaList != null && !currentCommodityAreaList.isEmpty()) {
            commodityAreaRepository.deleteAll(currentCommodityAreaList);
            commodity.setCommodityAreaList(null);
        }
        //清除商品备注
        CommodityRemark commodityRemark = commodity.getCommodityRemark();
        if (commodityRemark != null) {
            commodityRemarkRepository.delete(commodityRemark);
            commodity.setCommodityRemark(null);
        }
        //清除商品属性中间表 S2B获取上下游商品不能修改属性
        List<CommodityAttribute> commodityAttributeList = commodity.getCommodityAttributeList();
        if (commodityAttributeList != null && !commodityAttributeList.isEmpty() && isUpdateS2BDate) {
            commodityAttributeRepository.deleteAll(commodityAttributeList);
            commodity.setCommodityAttributeList(null);
        }

        //清除商品规格属性中间表
        List<CommodityUnitPriceAndPic> unitPriceAndPicList = commodity.getUnitPriceAndPicList();
        if (unitPriceAndPicList != null) {
            List<CommodityGoodsAttribute> commodityGoodsAttributeList = unitPriceAndPicList.stream().flatMap(commodityUnitPriceAndPic -> commodityUnitPriceAndPic.getAttributeAndValueList().stream()).collect(Collectors.toList());
            if (commodityGoodsAttributeList.size() > 0) {
                commodityGoodsAttributeRepository.deleteAll(commodityGoodsAttributeList);
            }
        }

        //如果可以修改商品属性，清掉之前的数据
        if (isUpdateAttribute != null && isUpdateAttribute) {
            //清除商品价格和图片中间表
            List<CommodityUnitPriceAndPic> currentUnitPriceAndPicList = commodity.getUnitPriceAndPicList();
            if (currentUnitPriceAndPicList != null && !currentUnitPriceAndPicList.isEmpty()) {
                commodityUnitPriceAndPicRepository.deleteAll(currentUnitPriceAndPicList);
                commodity.setUnitPriceAndPicList(null);
            }
        }
    }

    /**
     * 批量删除商品
     *
     * @param idList
     * @return
     */
    @Transactional
    @Override
    public String deleteBatchCommodity(UserLoginCacheDTO sysUser, List<Long> idList) {
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        //判断商品是否都存在
        List<Commodity> commodityList = commodityRepository.findAllByMemberIdAndMemberRoleIdAndIdIn(memberId, memberRoleId, idList);
        if (commodityList.isEmpty() || commodityList.size() != idList.size()) {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
        }
        //商品状态为待提交审核且从未提交过审核的商品才能删除
        commodityList = commodityList.stream().filter(commodity -> CommodityStatusEnum.Not_Submitted.getCode().equals(commodity.getStatus()) && commodity.getCheckTime() == null).collect(Collectors.toList());
        if (commodityList.isEmpty() || commodityList.size() != idList.size()) {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_STATUS_DELETE);
        }
        //首页数据统计
        try {
            List<OperateNoticeVO> operateNoticeVOList = new ArrayList<>();
            //待提交审核商品
            OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
            operateNoticeVO.setMemberId(memberId);
            operateNoticeVO.setRoleId(memberRoleId);
            operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
            operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_VALIFY_COMMIT.getCode());
            operateNoticeVO.setReduceCount((long) commodityList.size());
            operateNoticeVOList.add(operateNoticeVO);
            //商品总数
            operateNoticeVO = new OperateNoticeVO();
            operateNoticeVO.setMemberId(memberId);
            operateNoticeVO.setRoleId(memberRoleId);
            operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
            operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.PRODUCT_COUNT.getCode());
            operateNoticeVO.setReduceCount((long) commodityList.size());
            operateNoticeVOList.add(operateNoticeVO);
            reportControllerFeign.addOperateNoticeList(operateNoticeVOList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        commodityRepository.deleteAll(commodityList);
        return ResponseCode.SUCCESS.getMessage();
    }

    /**
     * 提交审核
     *
     * @param id
     * @return
     */
    @Override
    public String applyCheckCommodity(UserLoginCacheDTO sysUser, Long id) {
        //验证数据库中是否存在该数据
        Commodity commodity = commodityRepository.findById(id).orElse(null);
        if (commodity != null) {
            Integer current_status = commodity.getStatus();
            if (!CommodityStatusEnum.Not_Submitted.getCode().equals(current_status)) {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_STATUS_UNLEGAL);
            }
            Long time = System.currentTimeMillis();
            Integer new_status = CommodityStatusEnum.Not_Check.getCode();
            //持久化数据
            commodity.setStatus(new_status);
            commodity.setApplyTime(time);
            commodityRepository.saveAndFlush(commodity);

            CommodityCheckRecord commodityCheckRecord = new CommodityCheckRecord();
            commodityCheckRecord.setMemberRoleId(sysUser.getMemberRoleId());
            commodityCheckRecord.setMemberRoleName(sysUser.getMemberRoleName());
            commodityCheckRecord.setOperation(OperationEnum.Insert.getCode());
            commodityCheckRecord.setStatus(new_status);
            commodityCheckRecord.setCreateTime(time);
            commodityCheckRecord.setCommodityId(commodity.getId());
            commodityCheckRecordRepository.saveAndFlush(commodityCheckRecord);

            //首页数据统计
            try {
                List<OperateNoticeVO> operateNoticeVOList = new ArrayList<>();
                //会员待提交审核-1
                OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                operateNoticeVO.setMemberId(commodity.getMemberId());
                operateNoticeVO.setRoleId(commodity.getMemberRoleId());
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_VALIFY_COMMIT.getCode());
                operateNoticeVO.setReduceCount(1L);
                operateNoticeVOList.add(operateNoticeVO);
                //平台后台待审核商品+1
                if (CheckTypeEnum.PLATFORM_CHECK.getCode().equals(commodity.getCheckType())) {
                    operateNoticeVO = new OperateNoticeVO();
                    operateNoticeVO.setMemberId(0L);
                    operateNoticeVO.setRoleId(0L);
                    operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                    operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_CHECK_COMMIT.getCode());
                    operateNoticeVO.setIncreaseCount(1L);
                    operateNoticeVOList.add(operateNoticeVO);
                }
                reportControllerFeign.addOperateNoticeList(operateNoticeVOList);

                //发送消息
                SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
                systemMessageRequest.setMemberId(0L);
                systemMessageRequest.setRoleId(0L);
                systemMessageRequest.setMessageNotice(MessageTemplateCode.commodity_apply);
                List<String> params = new ArrayList<>();
                params.add(commodity.getMemberName());
                systemMessageRequest.setParams(params);
                systemMessageControllerFeign.sendSystemMessage(systemMessageRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ResponseCode.SUCCESS.getMessage();
        } else {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
        }
    }

    /**
     * 商品上架/下架--商品能力
     *
     * @param commodityShopRequest
     * @param isPublish            是否上架
     * @return
     */
    @Transactional
    @Override
    public String publishCommodity(CommodityShopRequest commodityShopRequest, Boolean isPublish) {
        OperateNoticeVO operateNoticeVO = new OperateNoticeVO();

        Long commodityId = commodityShopRequest.getId();
        Long storeId = commodityShopRequest.getStoreId();
        String storeName = commodityShopRequest.getStoreName();
        String storeLogo = commodityShopRequest.getStoreLogo();
        List<ShopRequest> shopList = commodityShopRequest.getShopList();
        //验证数据库中是否存在该商品
        Commodity commodity = commodityRepository.findById(commodityId).orElse(null);
        if (commodity != null) {
            //检查商品的状态
            Integer current_status = commodity.getStatus();
            if (isPublish) {
                if (!CommodityStatusEnum.Pass.getCode().equals(current_status) && !CommodityStatusEnum.On_Shelf.getCode().equals(current_status) && !CommodityStatusEnum.Off_Shelf.getCode().equals(current_status)) {
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_STATUS_UNLEGAL);
                }

                //待上架商品-1
                operateNoticeVO.setMemberId(commodity.getMemberId());
                operateNoticeVO.setRoleId(commodity.getMemberRoleId());
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_PUBLISH.getCode());
                operateNoticeVO.setReduceCount(1L);
            } else {
                if (!CommodityStatusEnum.On_Shelf.getCode().equals(current_status)) {
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_STATUS_UNLEGAL);
                }

                //待上架商品+1
                operateNoticeVO.setMemberId(commodity.getMemberId());
                operateNoticeVO.setRoleId(commodity.getMemberRoleId());
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_PUBLISH.getCode());
                operateNoticeVO.setIncreaseCount(1L);
            }
            //记录店铺信息
            commodity.setStoreId(storeId);
            commodity.setStoreName(storeName);
            commodity.setStoreLogo(storeLogo);

            //删除商品上架商城表
            commodityShopRepository.deleteCommodityShopByCommodityId(commodity.getId());

            //生成商品上架商城数据
            List<CommodityShop> commodityShopList = new ArrayList<>();
            shopList.forEach(shop -> {
                CommodityShop commodityShop = new CommodityShop();
                commodityShop.setShopId(shop.getShopId());
                commodityShop.setType(shop.getType());
                commodityShop.setEnvironment(shop.getEnvironment());
                commodityShop.setCommodity(commodity);
                commodityShopList.add(commodityShop);
            });
            commodity.setCommodityShopList(commodityShopList);

            //商品状态
            Integer new_status;
            if (commodityShopList.size() > 0) {
                new_status = CommodityStatusEnum.On_Shelf.getCode();
                commodity.setPublishTime(System.currentTimeMillis());
            } else {
                new_status = CommodityStatusEnum.Off_Shelf.getCode();
            }
            commodity.setStatus(new_status);
            commodity.setPublishTime(System.currentTimeMillis());
            commodityRepository.saveAndFlush(commodity);
            //同步es
            CommodityDetailResponse commodityDetailResponse = BeanUtil.copyProperties(commodity, CommodityDetailResponse.class);
            Boolean flag = syncEsCommodityService.publishCommodity(commodityDetailResponse);
            if (flag != null && flag) {
                try {
                    //首页数据统计
                    reportControllerFeign.addOperateNotice(operateNoticeVO);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return ResponseCode.SUCCESS.getMessage();
            } else {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_PUBLISH_FAIL);
            }
        } else {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
        }
    }

    /**
     * 批量商品上架/下架--商品能力
     *
     * @param commodityShopBatchRequest
     * @param isPublish                 是否上架
     * @return
     */
    @Transactional
    @Override
    public String publishCommodityBatch(UserLoginCacheDTO sysUser, CommodityShopBatchRequest commodityShopBatchRequest, Boolean isPublish) {
        OperateNoticeVO operateNoticeVO = new OperateNoticeVO();

        List<Long> commodityIdList = commodityShopBatchRequest.getIdList();
        Long storeId = commodityShopBatchRequest.getStoreId();
        String storeName = commodityShopBatchRequest.getStoreName();
        String storeLogo = commodityShopBatchRequest.getStoreLogo();
        List<ShopRequest> shopList = commodityShopBatchRequest.getShopList();
        //验证数据库中是否存在该商品
        List<Commodity> commodityList = commodityRepository.findAllById(commodityIdList);
        if (commodityIdList.size() != commodityList.size()) {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
        }

        //删除商品上架商城表
        commodityShopRepository.deleteCommodityShopByCommodityIdIn(commodityIdList);

        List<CommodityDetailResponse> commodityDetailResponseList = new ArrayList<>();
        commodityList.forEach(commodity -> {
            //检查商品的状态
            Integer current_status = commodity.getStatus();
            if (isPublish) {
                if (!CommodityStatusEnum.Pass.getCode().equals(current_status) && !CommodityStatusEnum.On_Shelf.getCode().equals(current_status) && !CommodityStatusEnum.Off_Shelf.getCode().equals(current_status)) {
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_STATUS_UNLEGAL);
                }
                commodity.setStoreId(storeId);
                commodity.setStoreName(storeName);
                commodity.setStoreLogo(storeLogo);

                //待上架商品-1
                operateNoticeVO.setMemberId(sysUser.getMemberId());
                operateNoticeVO.setRoleId(sysUser.getMemberRoleId());
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_PUBLISH.getCode());
                operateNoticeVO.setReduceCount((long) commodityDetailResponseList.size());
            } else {
                if (!CommodityStatusEnum.On_Shelf.getCode().equals(current_status)) {
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_STATUS_UNLEGAL);
                }

                //待上架商品+1
                operateNoticeVO.setMemberId(sysUser.getMemberId());
                operateNoticeVO.setRoleId(sysUser.getMemberRoleId());
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_PUBLISH.getCode());
                operateNoticeVO.setIncreaseCount((long) commodityDetailResponseList.size());
            }

            //生成商品上架商城数据
            List<CommodityShop> commodityShopList = new ArrayList<>();
            if (shopList != null && shopList.size() > 0) {
                shopList.forEach(shop -> {
                    CommodityShop commodityShop = new CommodityShop();
                    commodityShop.setShopId(shop.getShopId());
                    commodityShop.setType(shop.getType());
                    commodityShop.setEnvironment(shop.getEnvironment());
                    commodityShop.setCommodity(commodity);
                    commodityShopList.add(commodityShop);
                });
            }
            commodity.setCommodityShopList(commodityShopList);

            //商品状态
            Integer new_status;
            if (commodityShopList.size() > 0) {
                new_status = CommodityStatusEnum.On_Shelf.getCode();
                commodity.setPublishTime(System.currentTimeMillis());
            } else {
                new_status = CommodityStatusEnum.Off_Shelf.getCode();
            }
            commodity.setStatus(new_status);
            commodity.setPublishTime(System.currentTimeMillis());

            //同步搜索服务商品实体
            CommodityDetailResponse commodityDetailResponse = BeanUtil.copyProperties(commodity, CommodityDetailResponse.class);
            commodityDetailResponseList.add(commodityDetailResponse);
        });

        //数据持久化
        commodityRepository.saveAll(commodityList);

        //同步搜索服务
        Boolean flag = syncEsCommodityService.publishCommodityBatch(commodityDetailResponseList);
        if (flag != null && flag) {
            try {
                //首页数据统计
                reportControllerFeign.addOperateNotice(operateNoticeVO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_PUBLISH_FAIL);
        }

        return ResponseCode.SUCCESS.getMessage();
    }

    /**
     * 下架某个会员的所有商品--商品能力
     *
     * @param memberId     会员id
     * @param memberRoleId 会员角色id
     * @return
     */
    @Transactional
    @Override
    public Boolean offPublishAllCommodity(Long memberId, Long memberRoleId) {
        List<Long> commodityIdList = new ArrayList<>();
        //查询会员的所有商品
        List<Commodity> list = commodityRepository.findByMemberIdAndMemberRoleId(memberId, memberRoleId);
        List<Commodity> commodityList = list.stream().map(commodity -> {
            Integer status = commodity.getStatus();
            if (CommodityStatusEnum.On_Shelf.getCode().equals(status)) {
                commodityIdList.add(commodity.getId());
                commodity.setCommodityShopList(null);
                commodity.setStatus(CommodityStatusEnum.Off_Shelf.getCode());
                return commodity;
            } else {
                return null;
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());

        if (!commodityIdList.isEmpty()) {
            //删除商品上架商城表
            commodityShopRepository.deleteCommodityShopByCommodityIdIn(commodityIdList);
            commodityRepository.saveAll(commodityList);

            //同步ES数据
            syncEsCommodityService.offPublishAllCommodity(commodityIdList);

            try {
                //首页数据统计
                OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                //待上架商品+1
                operateNoticeVO.setMemberId(memberId);
                operateNoticeVO.setRoleId(memberRoleId);
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_PUBLISH.getCode());
                operateNoticeVO.setIncreaseCount(Long.valueOf(String.valueOf(commodityIdList.size())));
                reportControllerFeign.addOperateNotice(operateNoticeVO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 复制商品--商品能力
     *
     * @param simpleIdListRequest 商品Id集合
     * @param commodityType       商品类型
     * @return
     */
    @Transactional
    @Override
    public String copyCommodity(UserLoginCacheDTO sysUser, SimpleIdListRequest simpleIdListRequest, Integer commodityType) {
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();

        List<Commodity> commodityList = new ArrayList<>();
        List<OperateNoticeVO> operateNoticeVOList = new ArrayList<>();
        List<Long> idList = simpleIdListRequest.getIdList();
        if (idList == null || idList.size() <= 0) {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
        }

        idList.forEach(id -> {
            Commodity commodity = commodityRepository.findById(id).orElse(null);
            if (commodity != null) {
                //检查该商品是否形成引用闭环  S端获取B端 B端获取S端
                if (Objects.nonNull(commodity.getUpperMemberId()) && memberId.equals(commodity.getUpperMemberId())
                        && memberRoleId.equals(commodity.getUpperMemberRoleId())) {
                    throw new BusinessException(ResponseCode.CIRCULAR_REFERENCE);
                }
                Commodity newCommodity = new Commodity();
                CopyOptions copyOptions = new CopyOptions();
                String[] properties = new String[]{"id", "commodityAreaList", "commodityAttributeList", "unitPriceAndPicList", "commodityRemark", "commodityShopList"};
                copyOptions.setIgnoreProperties(properties);
                BeanUtil.copyProperties(commodity, newCommodity, copyOptions);
                //初始化
                newCommodity.setName(getNewCommodityName(memberId, memberRoleId, newCommodity.getName()));
                newCommodity.setApplyTime(null);
                newCommodity.setCheckTime(null);
                newCommodity.setPublishTime(null);
                newCommodity.setStatus(CommodityStatusEnum.Not_Submitted.getCode());
                newCommodity.setMemberId(memberId);
                newCommodity.setMemberName(sysUser.getCompany());
                newCommodity.setMemberRoleId(sysUser.getMemberRoleId());
                newCommodity.setMemberRoleName(sysUser.getMemberRoleName());
                newCommodity.setUserId(sysUser.getUserId());
                newCommodity.setUserName(sysUser.getUserName());
                newCommodity.setCreateTime(System.currentTimeMillis());
                if (CommodityTypeEnum.Upper.getCode().equals(commodityType)) {
                    newCommodity.setType(CommodityTypeEnum.Upper.getCode());
                    newCommodity.setUpperCommodityId(commodity.getId());
                    newCommodity.setUpperMemberId(commodity.getMemberId());
                    newCommodity.setUpperMemberName(commodity.getMemberName());
                    newCommodity.setUpperMemberRoleId(commodity.getMemberRoleId());
                    newCommodity.setUpperMemberRoleName(commodity.getMemberRoleName());
                    newCommodity.setIsUpdateAttribute(false);
                    //物流信息
                    LogisticsRequest logistics = newCommodity.getLogistics();
                    logistics.setSendAddress(null);
                    logistics.setTemplateId(null);
                    logistics.setCompany(null);
                    newCommodity.setLogistics(logistics);
                } else {
                    Integer type = commodity.getType();
                    if (type != null) {
                        newCommodity.setType(type);
                    }
                    Boolean isUpdateAttribute = commodity.getIsUpdateAttribute();
                    if (isUpdateAttribute != null) {
                        newCommodity.setIsUpdateAttribute(isUpdateAttribute);
                    }
                }

                //区域
                List<CommodityArea> commodityAreaList = commodity.getCommodityAreaList();
                if (commodityAreaList != null && !commodityAreaList.isEmpty()) {
                    CopyOptions commodityAreaCopyOptions = new CopyOptions();
                    commodityAreaCopyOptions.setIgnoreProperties("id", "commodity");
                    List<CommodityArea> newCommodityAreaList = commodityAreaList.stream().filter(Objects::nonNull).map(commodityArea -> {
                        CommodityArea newCommodityArea = new CommodityArea();
                        BeanUtil.copyProperties(commodityArea, newCommodityArea, commodityAreaCopyOptions);
                        newCommodityArea.setCommodity(newCommodity);
                        return newCommodityArea;
                    }).collect(Collectors.toList());
                    newCommodity.setCommodityAreaList(newCommodityAreaList);
                }
                //属性
                List<CommodityAttribute> commodityAttributeList = commodity.getCommodityAttributeList();
                if (commodityAttributeList != null && !commodityAttributeList.isEmpty()) {
                    List<CommodityAttribute> newCommodityAttributeList = commodityAttributeList.stream().filter(Objects::nonNull).map(commodityAttribute -> {
                        CommodityAttribute newCommodityAttribute = new CommodityAttribute();
                        newCommodityAttribute.setCustomerAttribute(commodityAttribute.getCustomerAttribute());
                        List<CustomerAttributeValue> collect = commodityAttribute.getCustomerAttributeValueList().stream().filter(Objects::nonNull).collect(Collectors.toList());
                        newCommodityAttribute.setCustomerAttributeValueList(collect);
                        newCommodityAttribute.setCommodity(newCommodity);
                        return newCommodityAttribute;
                    }).collect(Collectors.toList());
                    newCommodity.setCommodityAttributeList(newCommodityAttributeList);
                }
                //价格和图片
                List<CommodityUnitPriceAndPic> unitPriceAndPicList = commodity.getUnitPriceAndPicList();
                if (unitPriceAndPicList != null && !unitPriceAndPicList.isEmpty()) {
                    CopyOptions options = new CopyOptions();
                    options.setIgnoreProperties("id", "attributeAndValueList");
                    List<CommodityUnitPriceAndPic> collect = unitPriceAndPicList.stream().filter(Objects::nonNull).map(unitPriceAndPic -> {
                        CommodityUnitPriceAndPic newCommodityUnitPriceAndPic = new CommodityUnitPriceAndPic();
                        BeanUtil.copyProperties(unitPriceAndPic, newCommodityUnitPriceAndPic, options);
                        List<CommodityGoodsAttribute> newAttributeAndValueList = unitPriceAndPic.getAttributeAndValueList().stream().sorted(Comparator.comparing(CommodityGoodsAttribute::getId).reversed()).map(commodityGoodsAttribute -> {
                            CommodityGoodsAttribute newCommodityGoodsAttribute = new CommodityGoodsAttribute();
                            BeanUtil.copyProperties(commodityGoodsAttribute, newCommodityGoodsAttribute, options);
                            newCommodityGoodsAttribute.setCommodityUnitPriceAndPic(newCommodityUnitPriceAndPic);
                            return newCommodityGoodsAttribute;
                        }).collect(Collectors.toList());
                        newCommodityUnitPriceAndPic.setAttributeAndValueList(newAttributeAndValueList);
                        newCommodityUnitPriceAndPic.setCommodity(newCommodity);
                        if (CommodityTypeEnum.Upper.getCode().equals(commodityType)) {
                            newCommodityUnitPriceAndPic.setUpperCommoditySkuId(unitPriceAndPic.getId());
                        } else {
                            newCommodityUnitPriceAndPic.setUpperCommoditySkuId(unitPriceAndPic.getUpperCommoditySkuId());
                        }
                        return newCommodityUnitPriceAndPic;
                    }).collect(Collectors.toList());
                    newCommodity.setUnitPriceAndPicList(collect);
                }

                //备注
                CommodityRemark newCommodityRemark = new CommodityRemark();
                CommodityRemark commodityRemark = commodity.getCommodityRemark();
                List<CommodityRemarkImage> imageList = commodityRemark.getImageList();
                List<CommodityRemarkImage> newImageList = imageList.stream().map(commodityRemarkImage -> {
                    CommodityRemarkImage newCommodityRemarkImage = new CommodityRemarkImage();
                    newCommodityRemarkImage.setImageType(commodityRemarkImage.getImageType());
                    newCommodityRemarkImage.setLink(commodityRemarkImage.getLink());
                    newCommodityRemarkImage.setLinkType(commodityRemarkImage.getLinkType());
                    newCommodityRemarkImage.setUrl(commodityRemarkImage.getUrl());
                    newCommodityRemarkImage.setCommodityRemark(newCommodityRemark);
                    return newCommodityRemarkImage;
                }).collect(Collectors.toList());
                newCommodityRemark.setVideo(commodityRemark.getVideo());
                newCommodityRemark.setWord(commodityRemark.getWord());
                newCommodityRemark.setImageList(newImageList);
                newCommodity.setCommodityRemark(newCommodityRemark);
                commodityList.add(newCommodity);

                //首页数据统计
                try {
                    //商品总数
                    OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                    operateNoticeVO.setMemberId(newCommodity.getMemberId());
                    operateNoticeVO.setRoleId(newCommodity.getMemberRoleId());
                    operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                    operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.PRODUCT_COUNT.getCode());
                    operateNoticeVO.setIncreaseCount(1L);
                    operateNoticeVOList.add(operateNoticeVO);
                    //待提交审核商品
                    operateNoticeVO = new OperateNoticeVO();
                    operateNoticeVO.setMemberId(newCommodity.getMemberId());
                    operateNoticeVO.setRoleId(newCommodity.getMemberRoleId());
                    operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                    operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_VALIFY_COMMIT.getCode());
                    operateNoticeVO.setIncreaseCount(1L);
                    operateNoticeVOList.add(operateNoticeVO);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
            }
        });

        //数据库持久化对象
        commodityRepository.saveAll(commodityList);

        //调用平台管理服务->判断当前会员是否有自营商城
        ShopMemberInfoDTO dto = new ShopMemberInfoDTO();
        dto.setMemberId(sysUser.getMemberId());
        dto.setMemberRoleId(sysUser.getMemberRoleId());
        Wrapper<Boolean> existShop = shopRuleActivityFeign.existShop(dto);
        Boolean result = existShop.getData();

        commodityList.forEach(commodity -> {

        });


        commodityList.forEach(commodity -> {
            //根据id转成6位32进制字符
            String code = CodeUtils.digits32(commodity.getId(), Constants.CODE_NUM);
            commodity.setCode(Constants.COMMODITY_CODE_PREFIX + code);
            //设置审核 平台/商家
            if (!result) {
                commodity.setCheckType(CheckTypeEnum.PLATFORM_CHECK.getCode());//平台审核
            } else {
                commodity.setCheckType(CheckTypeEnum.MEMBER_CHECK.getCode());//商家审核
            }
        });
        //数据库持久化对象
        commodityRepository.saveAll(commodityList);

        //首页数据统计
        reportControllerFeign.addOperateNoticeList(operateNoticeVOList);
        return ResponseCode.SUCCESS.getMessage();
    }

    /**
     * 获取规格商品属性
     *
     * @param unitPriceAndPicId 规格商品id
     * @return
     */
    @Override
    public List<CommodityAttribute> getCommodityAttributeByUnitPriceAndPicId(UserLoginCacheDTO sysUser, Long unitPriceAndPicId) {
        List<CommodityAttribute> commodityAttributeList = new ArrayList<>();
        CommodityUnitPriceAndPic commodityUnitPriceAndPic = commodityUnitPriceAndPicRepository.findById(unitPriceAndPicId).orElse(null);
        if (commodityUnitPriceAndPic != null) {
            List<CommodityGoodsAttribute> attributeAndValueSet = commodityUnitPriceAndPic.getAttributeAndValueList();
            List<CommodityAttribute> commodityAttributeSet = commodityUnitPriceAndPic.getCommodity().getCommodityAttributeList();
            commodityAttributeSet.forEach(commodityAttribute -> {
                CustomerAttribute customerAttribute = commodityAttribute.getCustomerAttribute();
                if (customerAttribute != null) {
                    CommodityAttribute newCommodityAttribute = new CommodityAttribute();
                    Long attributeId = commodityAttribute.getCustomerAttribute().getId();
                    List<CustomerAttributeValue> customerAttributeValueList = customerAttribute.getCustomerAttributeValueList();
                    customerAttributeValueList.forEach(customerAttributeValue -> {
                        Long customerAttributeValueId = customerAttributeValue.getId();
                        attributeAndValueSet.forEach(commodityGoodsAttribute -> {
                            CustomerAttribute newCustomerAttribute = commodityGoodsAttribute.getCustomerAttribute();
                            Long commodityGoodsAttributeId = commodityGoodsAttribute.getCustomerAttribute().getId();
                            if (attributeId.longValue() == commodityGoodsAttributeId.longValue()) {
                                Long commodityGoodsAttributeValueId = commodityGoodsAttribute.getCustomerAttributeValue().getId();
                                if (customerAttributeValueId.longValue() == commodityGoodsAttributeValueId.longValue()) {
                                    newCommodityAttribute.setId(commodityGoodsAttribute.getId());
                                    newCommodityAttribute.setCustomerAttribute(newCustomerAttribute);
                                    List<CustomerAttributeValue> customerAttributeValueSet = new ArrayList<>();
                                    customerAttributeValueSet.add(customerAttributeValue);
                                    newCommodityAttribute.setCustomerAttributeValueList(customerAttributeValueSet);
                                    commodityAttributeList.add(newCommodityAttribute);
                                }
                            }
                        });
                    });
                }
            });
        }
        return commodityAttributeList;
    }

    /**
     * 获取不重复的商品名称
     *
     * @param memberId
     * @param name
     * @return
     */
    private String getNewCommodityName(Long memberId, Long memberRoleId, String name) {
        name = name + "_1";
        Boolean flag = commodityRepository.existsByMemberIdAndMemberRoleIdAndName(memberId, memberRoleId, name);
        if (flag) {
            return getNewCommodityName(memberId, memberRoleId, name);
        }
        return name;
    }

    /**
     * 查询商品列表(快捷修改商品单价)--商品能力
     *
     * @param pageVO                 分页实体
     * @param commodityDetailRequest 查询条件实体
     * @return
     */
    @Override
    public PageData<CommodityGoodsResponse> getCommodityPriceList(PageVO pageVO, CommodityDetailRequest commodityDetailRequest) {
        List<CommodityGoodsResponse> commodityGoodsResponseList = new ArrayList<>();
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Page<CommodityUnitPriceAndPic> list = commodityUnitPriceAndPicRepository.findAll(getCommodityDetailSpecification(commodityDetailRequest, null, null), page);
        List<CommodityUnitPriceAndPic> commodityUnitPriceAndPicList = list.getContent();
        for (CommodityUnitPriceAndPic commodityUnitPriceAndPic : commodityUnitPriceAndPicList) {
            Commodity commodity = commodityUnitPriceAndPic.getCommodity();
            CommodityGoodsResponse commodityGoodsResponse = new CommodityGoodsResponse();
            commodityGoodsResponse.setCommodityId(commodity.getId());
            commodityGoodsResponse.setId(commodityUnitPriceAndPic.getId());
            commodityGoodsResponse.setCode(Constants.COMMODITY_CODE_PREFIX + CodeUtils.digits32(commodityUnitPriceAndPic.getId(), Constants.CODE_NUM));
            if (commodityUnitPriceAndPic.getGoods() != null) {
                commodityGoodsResponse.setGoodsId(commodityUnitPriceAndPic.getGoods().getId());
            }
            commodityGoodsResponse.setUnitName(commodity.getUnitName());
            commodityGoodsResponse.setPriceType(commodity.getPriceType());
            commodityGoodsResponse.setStatus(commodity.getStatus());
            commodityGoodsResponse.setCustomerCategoryName(commodity.getCustomerCategory().getName());
            if (commodity.getBrand() != null) {
                commodityGoodsResponse.setBrandName(commodity.getBrand().getName());
            }

            //商品价格
            Map<String, Double> unitPrice = commodityUnitPriceAndPic.getUnitPrice();
            if (unitPrice != null && unitPrice.size() > 0) {
                commodityGoodsResponse.setMin(Collections.min(unitPrice.values()));
                commodityGoodsResponse.setMax(Collections.max(unitPrice.values()));
                commodityGoodsResponse.setUnitPrice(unitPrice);
            }
            //商品属性
            List<CommodityGoodsAttribute> attributeAndValueList = commodityUnitPriceAndPic.getAttributeAndValueList();
            String attribute = StringUtils.join(attributeAndValueList.stream().sorted(Comparator.comparing(CommodityGoodsAttribute::getId).reversed()).map(commodityGoodsAttribute -> commodityGoodsAttribute.getCustomerAttributeValue().getValue()).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR);
            if (StringUtils.isNotEmpty(attribute)) {
                commodityGoodsResponse.setName(commodity.getName() + Constants.COMMODITY_NAME_SPLIT_STR + attribute);
            } else {
                commodityGoodsResponse.setName(commodity.getName());
            }
            commodityGoodsResponse.setApplyTime(commodity.getApplyTime());
            commodityGoodsResponse.setIsMemberPrice(commodity.getIsMemberPrice());
            commodityGoodsResponse.setStatus(commodity.getStatus());
            commodityGoodsResponse.setMemberId(commodity.getMemberId());
            commodityGoodsResponse.setMemberName(commodity.getMemberName());
            commodityGoodsResponse.setMemberRoleId(commodity.getMemberRoleId());
            commodityGoodsResponse.setMemberRoleName(commodity.getMemberRoleName());
            commodityGoodsResponse.setMainPic(commodity.getMainPic());
            commodityGoodsResponse.setMinOrder(commodity.getMinOrder());
            commodityGoodsResponseList.add(commodityGoodsResponse);
        }
        return new PageData<>(list.getTotalElements(), commodityGoodsResponseList);
    }

    /**
     * 查询商品列表(按具体商品查询)--商品能力
     *
     * @param pageVO                 分页实体
     * @param commodityDetailRequest 查询条件实体
     * @return
     */
    @Override
    public PageData<CommodityGoodsResponse> getCommodityDetailList(PageVO pageVO, CommodityDetailRequest commodityDetailRequest, Long loginMemberId, Long loginMemberRoleId) {
        List<Long> shopIdList = commodityDetailRequest.getShopIdList();
        Long shopId = null;
        List<CommodityGoodsResponse> commodityGoodsResponseList = new ArrayList<>();
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Page<CommodityUnitPriceAndPic> list = commodityUnitPriceAndPicRepository.findAll(getCommodityDetailSpecification(commodityDetailRequest, loginMemberId, loginMemberRoleId), page);
        List<CommodityUnitPriceAndPic> commodityUnitPriceAndPicList = list.getContent();

        if (!commodityUnitPriceAndPicList.isEmpty()) {
            //查询当前登录用户的所有上级对应的会员等级
            Map<String, Integer> memberLevelMap = new HashMap<>();
            MemberFeignVO memberFeignVO = new MemberFeignVO();
            memberFeignVO.setMemberId(loginMemberId);
            memberFeignVO.setRoleId(loginMemberRoleId);
            Wrapper<List<MemberFeignLevelDetailVO>> subMemberLevels = memberLevelRightCreditControllerFeign.findSubMemberLevels(memberFeignVO);
            if(subMemberLevels != null && ResponseCode.SUCCESS.getCode() == subMemberLevels.getCode()){
                List<MemberFeignLevelDetailVO> data = subMemberLevels.getData();
                if(!CollectionUtils.isEmpty(data)){
                    data.stream().filter(memberFeignLevelDetailVO -> memberFeignLevelDetailVO.getRelType() == 1).forEach(memberFeignLevelDetailVO -> {
                        Long upperMemberId = memberFeignLevelDetailVO.getUpperMemberId();
                        Long upperRoleId = memberFeignLevelDetailVO.getUpperRoleId();
                        Integer level = memberFeignLevelDetailVO.getLevel();
                        memberLevelMap.put(upperMemberId + Constants.UNDERLINE_STR + upperRoleId, level);
                    });
                }
            }
            List<Object> resultList = null;
            if (shopIdList != null && shopIdList.size() > 0) {
                shopId = shopIdList.get(0);
                //组装redis键值格式
                List<HashMap<String, String[]>> keyFieldList = commodityUnitPriceAndPicList.stream().map(unitPriceAndPic -> {
                    HashMap<String, String[]> map = new HashMap<>();
                    String unitPriceAndPicId = CommonConstant.FREIGHT_SPACE_REDIS_KEY + shopIdList.get(0) + "_" + unitPriceAndPic.getId();
                    String commodityMemberId = String.valueOf(loginMemberId);
                    map.put(unitPriceAndPicId, new String[]{commodityMemberId, CommonConstant.FREIGHT_All});
                    return map;
                }).collect(Collectors.toList());

                //获取库存数据并赋值给每个进货单
                resultList = redisStringUtils.hMGetBatch(keyFieldList, Constants.REDIS_PRODUCT_INDEX);
            }

            for (int i = 0; i < commodityUnitPriceAndPicList.size(); i++) {
                CommodityUnitPriceAndPic commodityUnitPriceAndPic = commodityUnitPriceAndPicList.get(i);
                Long commodityUnitPriceAndPicId = commodityUnitPriceAndPic.getId();
                Commodity commodity = commodityUnitPriceAndPic.getCommodity();
                CommodityGoodsResponse commodityGoodsResponse = new CommodityGoodsResponse();
                commodityGoodsResponse.setCommodityId(commodity.getId());
                commodityGoodsResponse.setId(commodityUnitPriceAndPicId);
                commodityGoodsResponse.setCode(Constants.COMMODITY_CODE_PREFIX + CodeUtils.digits32(commodityUnitPriceAndPic.getId(), Constants.CODE_NUM));
                if (commodityUnitPriceAndPic.getGoods() != null) {
                    commodityGoodsResponse.setGoodsId(commodityUnitPriceAndPic.getGoods().getId());
                }
                commodityGoodsResponse.setUnitName(commodity.getUnitName());
                commodityGoodsResponse.setPriceType(commodity.getPriceType());
                commodityGoodsResponse.setStatus(commodity.getStatus());
                commodityGoodsResponse.setCustomerCategoryName(commodity.getCustomerCategory().getName());
                if (commodity.getBrand() != null) {
                    commodityGoodsResponse.setBrandName(commodity.getBrand().getName());
                }

                //设置商品默认价格
                Map<String, Double> unitPrice = commodityUnitPriceAndPic.getUnitPrice();
                if (unitPrice != null && unitPrice.size() > 0) {
                    commodityGoodsResponse.setMin(Collections.min(unitPrice.values()));
                    commodityGoodsResponse.setMax(Collections.max(unitPrice.values()));
                    commodityGoodsResponse.setUnitPrice(unitPrice);
                }
                //根据价格策略设置价格
                Long finalShopId = shopId;
                List<CommodityUnitPriceStrategy> unitPriceStrategyList = commodityUnitPriceAndPic.getCommodity().getUnitPriceStrategyList();
                List<CommodityUnitPriceStrategy> shopPriceStrategy = unitPriceStrategyList.stream().filter(unitPriceStrategy -> unitPriceStrategy.getShopId().equals(finalShopId) && unitPriceStrategy.getIsEnable() && !unitPriceStrategy.getIsMember()).collect(Collectors.toList());
                List<CommodityUnitPriceStrategy> memberPriceStrategy = unitPriceStrategyList.stream().filter(unitPriceStrategy -> unitPriceStrategy.getShopId().equals(finalShopId) && unitPriceStrategy.getIsEnable() && unitPriceStrategy.getIsMember()).collect(Collectors.toList());

                //用于判断是按商城设置价格还是按会员/会员等级来设置价格
                boolean flag = true;
                //根据价格策略的会员来设置价格
                for (CommodityUnitPriceStrategy commodityUnitPriceStrategy : memberPriceStrategy) {
                    List<CommodityMemberUnitPrice> memberUnitPriceList = commodityUnitPriceStrategy.getMemberUnitPriceList();
                    Integer applyType = commodityUnitPriceStrategy.getApplyType();
                    if(UnitPriceStrategyApplyTypeEnum.Member.getCode().equals(applyType)){
                        List<CommodityMember> commodityMemberList = commodityUnitPriceStrategy.getCommodityMemberList();
                        for (CommodityMember commodityMember : commodityMemberList) {
                            Long memberId = commodityMember.getMemberId();
                            Long memberRoleId = commodityMember.getMemberRoleId();
                            if (memberId.equals(loginMemberId) && memberRoleId.equals(loginMemberRoleId)) {
                                for (CommodityMemberUnitPrice commodityMemberUnitPrice : memberUnitPriceList) {
                                    CommodityUnitPriceAndPic commodityUnitPrice = commodityMemberUnitPrice.getCommodityUnitPrice();
                                    if (commodityUnitPrice.getId().equals(commodityUnitPriceAndPicId)) {
                                        Map<String, Double> memberUnitPrice = commodityMemberUnitPrice.getUnitPrice();
                                        commodityGoodsResponse.setMin(commodityUnitPriceStrategy.getMin());
                                        commodityGoodsResponse.setMax(commodityUnitPriceStrategy.getMax());
                                        commodityGoodsResponse.setUnitPrice(memberUnitPrice);
                                        flag = false;
                                    }
                                }
                            }
                        }
                    }else{
                        List<CommodityMemberLevel> commodityMemberLevelList = commodityUnitPriceStrategy.getCommodityMemberLevelList();
                        for (CommodityMemberLevel commodityMemberLevel : commodityMemberLevelList) {
                            Long memberRoleId = commodityMemberLevel.getMemberRoleId();
                            Integer memberLevel = commodityMemberLevel.getLevel();
                            Integer loginMemberLevel = memberLevelMap.get(commodity.getMemberId() + Constants.UNDERLINE_STR + commodity.getMemberRoleId());
                            if (memberRoleId.equals(loginMemberRoleId) && memberLevel.equals(loginMemberLevel == null ? 0 : loginMemberLevel)) {
                                for (CommodityMemberUnitPrice commodityMemberUnitPrice : memberUnitPriceList) {
                                    CommodityUnitPriceAndPic commodityUnitPrice = commodityMemberUnitPrice.getCommodityUnitPrice();
                                    if (commodityUnitPrice.getId().equals(commodityUnitPriceAndPicId)) {
                                        Map<String, Double> memberUnitPrice = commodityMemberUnitPrice.getUnitPrice();
                                        commodityGoodsResponse.setMin(commodityUnitPriceStrategy.getMin());
                                        commodityGoodsResponse.setMax(commodityUnitPriceStrategy.getMax());
                                        commodityGoodsResponse.setUnitPrice(memberUnitPrice);
                                        flag = false;
                                    }
                                }
                            }
                        }
                    }
                }
                if (flag) {
                    //根据价格策略的商城来设置价格
                    shopPriceStrategy.forEach(commodityUnitPriceStrategy -> {
                        List<CommodityMemberUnitPrice> memberUnitPriceList = commodityUnitPriceStrategy.getMemberUnitPriceList();
                        memberUnitPriceList.forEach(commodityMemberUnitPrice -> {
                            CommodityUnitPriceAndPic commodityUnitPrice = commodityMemberUnitPrice.getCommodityUnitPrice();
                            if (commodityUnitPrice.getId().equals(commodityUnitPriceAndPicId)) {
                                Map<String, Double> memberUnitPrice = commodityMemberUnitPrice.getUnitPrice();
                                commodityGoodsResponse.setMin(commodityUnitPriceStrategy.getMin());
                                commodityGoodsResponse.setMax(commodityUnitPriceStrategy.getMax());
                                commodityGoodsResponse.setUnitPrice(memberUnitPrice);
                            }
                        });
                    });
                }
                //商品属性
                List<CommodityGoodsAttribute> attributeAndValueList = commodityUnitPriceAndPic.getAttributeAndValueList();
                String attribute = StringUtils.join(attributeAndValueList.stream().sorted(Comparator.comparing(CommodityGoodsAttribute::getId).reversed()).map(commodityGoodsAttribute -> commodityGoodsAttribute.getCustomerAttributeValue().getValue()).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR);
                if (StringUtils.isNotEmpty(attribute)) {
                    commodityGoodsResponse.setName(commodity.getName() + Constants.COMMODITY_NAME_SPLIT_STR + attribute);
                } else {
                    commodityGoodsResponse.setName(commodity.getName());
                }
                //商品图片
                String[] commodityPic = commodityUnitPriceAndPic.getCommodityPic();
                if (commodityPic != null && commodityPic.length > 0) {
                    commodityGoodsResponse.setMainPic(commodityPic[0]);
                } else {
                    commodityGoodsResponse.setMainPic(commodity.getMainPic());
                }
                commodityGoodsResponse.setApplyTime(commodity.getApplyTime());
                commodityGoodsResponse.setIsMemberPrice(commodity.getIsMemberPrice());
                commodityGoodsResponse.setStatus(commodity.getStatus());
                commodityGoodsResponse.setMemberId(commodity.getMemberId());
                commodityGoodsResponse.setMemberName(commodity.getMemberName());
                commodityGoodsResponse.setMemberRoleId(commodity.getMemberRoleId());
                commodityGoodsResponse.setMemberRoleName(commodity.getMemberRoleName());
                commodityGoodsResponse.setMinOrder(commodity.getMinOrder());
                commodityGoodsResponse.setTaxRate(commodity.getTaxRate());

                Integer type = commodity.getType();
                commodityGoodsResponse.setType(type);
                //上游商品才有值
                if (CommodityTypeEnum.Upper.getCode().equals(type)) {
                    commodityGoodsResponse.setCommodityUnitPriceAndPicId(commodityUnitPriceAndPic.getUpperCommoditySkuId());
                    commodityGoodsResponse.setUpperMemberId(commodity.getUpperMemberId());
                    commodityGoodsResponse.setUpperMemberName(commodity.getUpperMemberName());
                    commodityGoodsResponse.setUpperMemberRoleId(commodity.getUpperMemberRoleId());
                    commodityGoodsResponse.setUpperMemberRoleName(commodity.getUpperMemberRoleName());
                }

                //计算当前商品的库存数
                if (resultList != null && resultList.size() > 0) {
                    List<String> stockList = (List<String>) resultList.get(i);
                    if (stockList != null && !stockList.isEmpty()) {
                        List<String> collect = stockList.stream().filter(StrUtil::isNotEmpty).collect(Collectors.toList());
                        if (!collect.isEmpty()) {
                            Double stockCount = collect.stream().map(Double::parseDouble).reduce(Double::sum).get();
                            commodityGoodsResponse.setStockCount(stockCount);
                        }
                    }
                }

                LogisticsResponse logisticsResponse = new LogisticsResponse();
                BeanUtil.copyProperties(commodity.getLogistics(), logisticsResponse);
                commodityGoodsResponse.setLogistics(logisticsResponse);
                //是否跨境商品
                commodityGoodsResponse.setIsCrossBorder(commodity.getIsCrossBorder());

                commodityGoodsResponseList.add(commodityGoodsResponse);
            }
        }
        return new PageData<>(list.getTotalElements(), commodityGoodsResponseList);
    }

    /**
     * 查询商品列表(按具体商品查询)--库存设置
     *
     * @param pageVO                 分页实体
     * @param commodityDetailRequest 查询条件实体
     * @param memberRoleType         会员角色类型
     * @return
     */
    @Override
    public PageData<CommodityStockResponse> getCommodityDetailStockList(PageVO pageVO, CommodityDetailRequest commodityDetailRequest, Integer memberRoleType) {
        List<CommodityStockResponse> commodityStockResponseList = new ArrayList<>();
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Page<CommodityUnitPriceAndPic> list = commodityUnitPriceAndPicRepository.findAll(getCommodityDetailSpecification(commodityDetailRequest, null, null), page);
        List<CommodityUnitPriceAndPic> commodityUnitPriceAndPicList = list.getContent();
        //适用会员角色信息得为服务消费者 且商城类型为企业商城
        if (!commodityUnitPriceAndPicList.isEmpty()) {
            HashMap<Long, Double> commodityStockMap = new HashMap<>();
            //查询所有上游会员商品库存
            List<Long> upperCommoditySkuIdList = commodityUnitPriceAndPicList.stream().map(CommodityUnitPriceAndPic::getUpperCommoditySkuId).collect(Collectors.toList());
            if (upperCommoditySkuIdList.size() > 0) {
                //筛选适用会员角色为消费者的sku
                commodityStockMap = this.getUpperCommoditySkuStock(commodityDetailRequest.getMemberId(), commodityDetailRequest.getShopType(), upperCommoditySkuIdList);
            }

            for (CommodityUnitPriceAndPic commodityUnitPriceAndPic : commodityUnitPriceAndPicList) {
                CommodityStockResponse commodityStockResponse = new CommodityStockResponse();
                Commodity commodity = commodityUnitPriceAndPic.getCommodity();
                commodityStockResponse.setCommodityId(commodity.getId());
                commodityStockResponse.setId(commodityUnitPriceAndPic.getId());
                commodityStockResponse.setCode(Constants.COMMODITY_CODE_PREFIX + CodeUtils.digits32(commodityUnitPriceAndPic.getId(), Constants.CODE_NUM));
                if (commodityUnitPriceAndPic.getGoods() != null) {
                    commodityStockResponse.setGoodsId(commodityUnitPriceAndPic.getGoods().getId());
                    commodityStockResponse.setGoodsCode(commodityUnitPriceAndPic.getGoods().getCode());
                    commodityStockResponse.setGoodsName(commodityUnitPriceAndPic.getGoods().getName());
                }
                commodityStockResponse.setUnitName(commodity.getUnitName());
                commodityStockResponse.setCustomerCategoryName(commodity.getCustomerCategory().getName());
                if (commodity.getBrand() != null) {
                    commodityStockResponse.setBrandName(commodity.getBrand().getName());
                }
                //商品属性
                List<CommodityGoodsAttribute> attributeAndValueList = commodityUnitPriceAndPic.getAttributeAndValueList();
                String attribute = StringUtils.join(attributeAndValueList.stream().sorted(Comparator.comparing(CommodityGoodsAttribute::getId).reversed()).map(commodityGoodsAttribute -> commodityGoodsAttribute.getCustomerAttributeValue().getValue()).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR);
                if (StringUtils.isNotEmpty(attribute)) {
                    commodityStockResponse.setName(commodity.getName() + Constants.COMMODITY_NAME_SPLIT_STR + attribute);
                } else {
                    commodityStockResponse.setName(commodity.getName());
                }
                //上游供应商
                Long upperCommoditySkuId = commodityUnitPriceAndPic.getUpperCommoditySkuId();
                if (upperCommoditySkuId != null && upperCommoditySkuId > 0) {
                    commodityStockResponse.setUpperMemberName(commodity.getUpperMemberName());
                    commodityStockResponse.setUpperStockCount(commodityStockMap.get(upperCommoditySkuId));
                }

                commodityStockResponseList.add(commodityStockResponse);
            }
        }
        if (CollectionUtils.isEmpty(commodityStockResponseList)) {
            return new PageData<>(0L, new ArrayList<>());
        }
        return new PageData<>(list.getTotalElements(), commodityStockResponseList);
    }

    /**
     * 获取上级供应商的商品库存
     *
     * @param memberId
     * @param shopType
     * @param commoditySkuIdList
     * @return
     */
    @Override
    public HashMap<Long, Double> getUpperCommoditySkuStock(Long memberId, Integer shopType, List<Long> commoditySkuIdList) {
        HashMap<Long, Double> commodityStockMap = new HashMap<>();
        //获取相同商城类型的所有商城id
        Map<String, String> shopMap = redisStringUtils.hGetAll(Constants.REDIS_KEY_SHOP, Constants.REDIS_PLATFORM_MANAGE_INDEX);
        List<Long> shopIdList = shopMap.values().stream().map(s -> {
            JSONObject jsonObject = JSONUtil.parseObj(s);
            Integer type = jsonObject.getInt("type");
            if (shopType != null) {
                if (shopType.equals(type)) {
                    return jsonObject.getLong("id");
                } else {
                    return null;
                }
            } else {
                return jsonObject.getLong("id");
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());

        //组装redis查询key
        List<HashMap<String, String[]>> keyFieldList = new ArrayList<>();
        commoditySkuIdList.forEach(commoditySkuIdId -> shopIdList.forEach(shopId -> {
            HashMap<String, String[]> map = new HashMap<>();
            String unitPriceAndPicId = CommonConstant.FREIGHT_SPACE_REDIS_KEY + shopId + "_" + commoditySkuIdId;
            String commodityMemberId = String.valueOf(memberId);
            map.put(unitPriceAndPicId, new String[]{commodityMemberId, CommonConstant.FREIGHT_All});
            keyFieldList.add(map);
        }));

        //一次性查询所有商品在不同商城的库存
        List<Object> resultList = redisStringUtils.hMGetBatch(keyFieldList, Constants.REDIS_PRODUCT_INDEX);
        //同一个商品在同一个类型商城取最大的库存
        int index = 0;
        for (Long commoditySkuId : commoditySkuIdList) {
            double maxStockCount = 0;
            for (Long ignored : shopIdList) {
                List<String> stockList = (List<String>) resultList.get(index++);
                if (stockList != null && !stockList.isEmpty()) {
                    List<String> collect = stockList.stream().filter(StrUtil::isNotEmpty).collect(Collectors.toList());
                    if (!collect.isEmpty()) {
                        Double stockCount = collect.stream().map(Double::parseDouble).reduce(Double::sum).get();
                        if (stockCount > maxStockCount) {
                            maxStockCount = stockCount;
                        }
                    }
                }
            }
            commodityStockMap.put(commoditySkuId, maxStockCount);
        }

        return commodityStockMap;
    }

    /**
     * 批量获取商品价格
     *
     * @param unitPriceAndPicIdList
     * @return
     */
    @Override
    public Map<Long, Map<String, Double>> getCommodityPriceBatch(Long shopId, List<Long> unitPriceAndPicIdList, Long loginMemberId, Long loginMemberRoleId) {
        boolean flag = true;
        Map<Long, Map<String, Double>> result = new HashMap<>();
        //查询登录用户的所有上级对应的会员等级
        Map<String, Integer> memberLevelMap = new HashMap<>();
        MemberFeignVO memberFeignVO = new MemberFeignVO();
        memberFeignVO.setMemberId(loginMemberId);
        memberFeignVO.setRoleId(loginMemberRoleId);
        Wrapper<List<MemberFeignLevelDetailVO>> subMemberLevels = memberLevelRightCreditControllerFeign.findSubMemberLevels(memberFeignVO);
        if(subMemberLevels != null && ResponseCode.SUCCESS.getCode() == subMemberLevels.getCode()){
            List<MemberFeignLevelDetailVO> data = subMemberLevels.getData();
            if(!CollectionUtils.isEmpty(data)){
                data.stream().filter(memberFeignLevelDetailVO -> memberFeignLevelDetailVO.getRelType() == 1).forEach(memberFeignLevelDetailVO -> {
                    Long upperMemberId = memberFeignLevelDetailVO.getUpperMemberId();
                    Long upperRoleId = memberFeignLevelDetailVO.getUpperRoleId();
                    Integer level = memberFeignLevelDetailVO.getLevel();
                    memberLevelMap.put(upperMemberId + Constants.UNDERLINE_STR + upperRoleId, level);
                });
            }
        }
        //先查询商品价格
        List<CommodityUnitPriceAndPic> commodityUnitPriceAndPicList = commodityUnitPriceAndPicRepository.findAllById(unitPriceAndPicIdList);
        commodityUnitPriceAndPicList.forEach(commodityUnitPriceAndPic -> result.put(commodityUnitPriceAndPic.getId(), commodityUnitPriceAndPic.getUnitPrice()));
        //如果存在价格策略设置的价格
        List<CommodityMemberUnitPrice> commodityMemberUnitPriceList = commodityMemberUnitPriceRepository.findByCommodityUnitPriceIdInAndCommodityUnitPriceStrategyIsEnableAndCommodityUnitPriceStrategyShopId(unitPriceAndPicIdList, true, shopId);
        List<CommodityMemberUnitPrice> shopPriceStrategy = commodityMemberUnitPriceList.stream().filter(commodityMemberUnitPrice -> !commodityMemberUnitPrice.getCommodityUnitPriceStrategy().getIsMember()).collect(Collectors.toList());
        List<CommodityMemberUnitPrice> memberPriceStrategy = commodityMemberUnitPriceList.stream().filter(commodityMemberUnitPrice -> commodityMemberUnitPrice.getCommodityUnitPriceStrategy().getIsMember()).collect(Collectors.toList());
        //价格策略对应的会员价格
        for (CommodityMemberUnitPrice commodityMemberUnitPrice : memberPriceStrategy) {
            Commodity commodity = commodityMemberUnitPrice.getCommodityUnitPrice().getCommodity();
            Integer applyType = commodityMemberUnitPrice.getCommodityUnitPriceStrategy().getApplyType();
            if(UnitPriceStrategyApplyTypeEnum.Member.getCode().equals(applyType)){
                List<CommodityMember> commodityMemberList = commodityMemberUnitPrice.getCommodityUnitPriceStrategy().getCommodityMemberList();
                for (CommodityMember commodityMember : commodityMemberList) {
                    Long priceStrategyMemberId = commodityMember.getMemberId();
                    Long priceStrategyMemberRoleId = commodityMember.getMemberRoleId();
                    if (priceStrategyMemberId.equals(loginMemberId) && priceStrategyMemberRoleId.equals(loginMemberRoleId)) {
                        result.put(commodityMemberUnitPrice.getCommodityUnitPrice().getId(), commodityMemberUnitPrice.getUnitPrice());
                        flag = false;
                    }
                }
            }else{
                List<CommodityMemberLevel> commodityMemberLevelList = commodityMemberUnitPrice.getCommodityUnitPriceStrategy().getCommodityMemberLevelList();
                for (CommodityMemberLevel commodityMemberLevel : commodityMemberLevelList) {
                    Long memberRoleId = commodityMemberLevel.getMemberRoleId();
                    Integer level = commodityMemberLevel.getLevel();
                    Integer loginMemberLevel = memberLevelMap.get(commodity.getMemberId() + Constants.UNDERLINE_STR + commodity.getMemberRoleId());
                    if (memberRoleId.equals(loginMemberRoleId) && level.equals(loginMemberLevel == null ? 0 : loginMemberLevel)) {
                        result.put(commodityMemberUnitPrice.getCommodityUnitPrice().getId(), commodityMemberUnitPrice.getUnitPrice());
                        flag = false;
                    }
                }
            }
        }
        //价格策略对应的商城价格
        if (flag) {
            shopPriceStrategy.forEach(commodityMemberUnitPrice -> result.put(commodityMemberUnitPrice.getCommodityUnitPrice().getId(), commodityMemberUnitPrice.getUnitPrice()));
        }
        return result;
    }

    /**
     * 批量查询商品价格和是否允许使用会员权益
     *
     * @return
     */
    @Override
    public Map<Long, CommodityPriceResponse> getCommodityPriceAndMemberPriceBatch(Long shopId, List<Long> unitPriceAndPicIdList, Long loginMemberId, Long loginMemberRoleId) {
        boolean flag = true;
        Map<Long, CommodityPriceResponse> result = new HashMap<>();
        //查询登录用户的所有上级对应的会员等级
        Map<String, Integer> memberLevelMap = new HashMap<>();
        MemberFeignVO memberFeignVO = new MemberFeignVO();
        memberFeignVO.setMemberId(loginMemberId);
        memberFeignVO.setRoleId(loginMemberRoleId);
        Wrapper<List<MemberFeignLevelDetailVO>> subMemberLevels = memberLevelRightCreditControllerFeign.findSubMemberLevels(memberFeignVO);
        if(subMemberLevels != null && ResponseCode.SUCCESS.getCode() == subMemberLevels.getCode()){
            List<MemberFeignLevelDetailVO> data = subMemberLevels.getData();
            if(!CollectionUtils.isEmpty(data)){
                data.stream().filter(memberFeignLevelDetailVO -> memberFeignLevelDetailVO.getRelType() == 1).forEach(memberFeignLevelDetailVO -> {
                    Long upperMemberId = memberFeignLevelDetailVO.getUpperMemberId();
                    Long upperRoleId = memberFeignLevelDetailVO.getUpperRoleId();
                    Integer level = memberFeignLevelDetailVO.getLevel();
                    memberLevelMap.put(upperMemberId + Constants.UNDERLINE_STR + upperRoleId, level);
                });
            }
        }
        //先查询商品价格
        List<CommodityUnitPriceAndPic> commodityUnitPriceAndPicList = commodityUnitPriceAndPicRepository.findAllById(unitPriceAndPicIdList);
        commodityUnitPriceAndPicList.forEach(commodityUnitPriceAndPic -> {
            CommodityPriceResponse commodityPriceResponse = new CommodityPriceResponse();
            commodityPriceResponse.setIsMemberPrice(commodityUnitPriceAndPic.getCommodity().getIsMemberPrice());
            commodityPriceResponse.setCommodityPrice(commodityUnitPriceAndPic.getUnitPrice());
            result.put(commodityUnitPriceAndPic.getId(), commodityPriceResponse);
        });
        //如果存在价格策略设置的价格
        List<CommodityMemberUnitPrice> commodityMemberUnitPriceList = commodityMemberUnitPriceRepository.findByCommodityUnitPriceIdInAndCommodityUnitPriceStrategyIsEnableAndCommodityUnitPriceStrategyShopId(unitPriceAndPicIdList, true, shopId);
        List<CommodityMemberUnitPrice> shopPriceStrategy = commodityMemberUnitPriceList.stream().filter(commodityMemberUnitPrice -> !commodityMemberUnitPrice.getCommodityUnitPriceStrategy().getIsMember()).collect(Collectors.toList());
        List<CommodityMemberUnitPrice> memberPriceStrategy = commodityMemberUnitPriceList.stream().filter(commodityMemberUnitPrice -> commodityMemberUnitPrice.getCommodityUnitPriceStrategy().getIsMember()).collect(Collectors.toList());
        //价格策略对应的会员价格
        for (CommodityMemberUnitPrice commodityMemberUnitPrice : memberPriceStrategy) {
            Commodity commodity = commodityMemberUnitPrice.getCommodityUnitPrice().getCommodity();
            Integer applyType = commodityMemberUnitPrice.getCommodityUnitPriceStrategy().getApplyType();
            if(UnitPriceStrategyApplyTypeEnum.Member.getCode().equals(applyType)){
                List<CommodityMember> commodityMemberList = commodityMemberUnitPrice.getCommodityUnitPriceStrategy().getCommodityMemberList();
                for (CommodityMember commodityMember : commodityMemberList) {
                    Long priceStrategyMemberId = commodityMember.getMemberId();
                    Long priceStrategyMemberRoleId = commodityMember.getMemberRoleId();
                    if (priceStrategyMemberId.equals(loginMemberId) && priceStrategyMemberRoleId.equals(loginMemberRoleId)) {
                        CommodityPriceResponse memberCommodityPriceResponse = new CommodityPriceResponse();
                        memberCommodityPriceResponse.setIsMemberPrice(commodityMemberUnitPrice.getCommodityUnitPriceStrategy().getCommodity().getIsMemberPrice());
                        memberCommodityPriceResponse.setCommodityPrice(commodityMemberUnitPrice.getUnitPrice());
                        result.put(commodityMemberUnitPrice.getCommodityUnitPrice().getId(), memberCommodityPriceResponse);
                        flag = false;
                    }
                }
            }else{
                List<CommodityMemberLevel> commodityMemberLevelList = commodityMemberUnitPrice.getCommodityUnitPriceStrategy().getCommodityMemberLevelList();
                for (CommodityMemberLevel commodityMemberLevel : commodityMemberLevelList) {
                    Long memberRoleId = commodityMemberLevel.getMemberRoleId();
                    Integer level = commodityMemberLevel.getLevel();
                    Integer loginMemberLevel = memberLevelMap.get(commodity.getMemberId() + Constants.UNDERLINE_STR + commodity.getMemberRoleId());
                    if (memberRoleId.equals(loginMemberRoleId) && level.equals(loginMemberLevel == null ? 0 : loginMemberLevel)) {
                        CommodityPriceResponse memberCommodityPriceResponse = new CommodityPriceResponse();
                        memberCommodityPriceResponse.setIsMemberPrice(commodityMemberUnitPrice.getCommodityUnitPriceStrategy().getCommodity().getIsMemberPrice());
                        memberCommodityPriceResponse.setCommodityPrice(commodityMemberUnitPrice.getUnitPrice());
                        result.put(commodityMemberUnitPrice.getCommodityUnitPrice().getId(), memberCommodityPriceResponse);
                        flag = false;
                    }
                }
            }
        }
        //价格策略对应的商城价格
        if (flag) {
            shopPriceStrategy.forEach(commodityMemberUnitPrice -> {
                CommodityPriceResponse memberCommodityPriceResponse = new CommodityPriceResponse();
                memberCommodityPriceResponse.setIsMemberPrice(commodityMemberUnitPrice.getCommodityUnitPriceStrategy().getCommodity().getIsMemberPrice());
                memberCommodityPriceResponse.setCommodityPrice(commodityMemberUnitPrice.getUnitPrice());
                result.put(commodityMemberUnitPrice.getCommodityUnitPrice().getId(), memberCommodityPriceResponse);
            });
        }
        return result;
    }

    /**
     * 获取商品价格
     *
     * @param unitPriceAndPicId
     * @return
     */
    @Override
    public Map<String, Double> getCommodityPrice(UserLoginCacheDTO sysUser, Long unitPriceAndPicId) {
        CommodityUnitPriceAndPic unitPriceAndPic = commodityUnitPriceAndPicRepository.findById(unitPriceAndPicId).orElse(null);
        if (unitPriceAndPic != null) {
            return unitPriceAndPic.getUnitPrice();
        } else {
            return new HashMap<>();
        }
    }

    /**
     * 修改商品价格
     *
     * @param unitPriceRequest
     * @return
     */
    @Transactional
    @Override
    public String updateCommodityPrice(UserLoginCacheDTO sysUser, UnitPriceRequest unitPriceRequest) {
        Long memberId = sysUser.getMemberId();
        Long unitPriceAndPicId = unitPriceRequest.getId();
        if (unitPriceAndPicId != null && unitPriceAndPicId > 0) {
            CommodityUnitPriceAndPic unitPriceAndPic = commodityUnitPriceAndPicRepository.findById(unitPriceAndPicId).orElse(null);
            if (unitPriceAndPic != null) {
                Commodity commodity = unitPriceAndPic.getCommodity();
                //判断是否有该商品的权限
                Long commodityMemberId = commodity.getMemberId();
                if (commodityMemberId.longValue() == memberId.longValue()) {
                    Map<String, Double> unitPrice = unitPriceRequest.getUnitPrice();
                    unitPriceAndPic.setUnitPrice(unitPrice);

                    //计算商品的最大值和最小值
                    List<Map<String, Double>> collect = commodity.getUnitPriceAndPicList().stream().filter(commodityUnitPriceAndPic -> commodityUnitPriceAndPic != null && commodityUnitPriceAndPic.getUnitPrice() != null && commodityUnitPriceAndPic.getUnitPrice().size() > 0).map(CommodityUnitPriceAndPic::getUnitPrice).collect(Collectors.toList());
                    if (!collect.isEmpty()) {
                        Double min = Collections.min(collect.stream().map(m -> Collections.min(m.values())).collect(Collectors.toList()));
                        Double max = Collections.max(collect.stream().map(m -> Collections.max(m.values())).collect(Collectors.toList()));
                        commodity.setMin(min);
                        commodity.setMax(max);
                    } else {
                        commodity.setMin(0d);
                        commodity.setMax(0d);
                    }
                    unitPriceAndPic.setCommodity(commodity);
                    commodityUnitPriceAndPicRepository.saveAndFlush(unitPriceAndPic);

                    Integer status = commodity.getStatus();
                    if (CommodityStatusEnum.On_Shelf.getCode().equals(status)) {
                        CommodityDetailResponse commodityDetailResponse = new CommodityDetailResponse();
                        BeanUtil.copyProperties(commodity, commodityDetailResponse);
                        Boolean flag = syncEsCommodityService.updateCommodityPrice(commodityDetailResponse);
                        if (flag) {
                            return ResponseCode.SUCCESS.getMessage();
                        } else {
                            return ResponseCode.SERVICE_ERROR.getMessage();
                        }
                    }
                    return ResponseCode.SUCCESS.getMessage();
                }
            }
        }
        throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
    }

    /**
     * 查询价格策略列表--商品能力
     *
     * @param pageVO
     * @param sysUser
     * @param unitPriceStrategyRequest
     * @return
     */
    @Override
    public Page<CommodityUnitPriceStrategy> getUnitPriceStrategyList(PageVO pageVO, UserLoginCacheDTO sysUser, UnitPriceStrategyRequest unitPriceStrategyRequest) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return commodityUnitPriceStrategyRepository.findAll(getCommodityUnitPriceStrategySpecification(sysUser, unitPriceStrategyRequest), page);
    }

    /**
     * 新增/修改价格策略--商品能力
     *
     * @param sysUser
     * @param unitPriceStrategyAddRequest
     * @return
     */
    @Transactional
    @Override
    public Long saveOrUpdateUnitPriceStrategy(UserLoginCacheDTO sysUser, UnitPriceStrategyAddRequest unitPriceStrategyAddRequest) {
        Long shopId = unitPriceStrategyAddRequest.getShopId();
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        Long id = unitPriceStrategyAddRequest.getId();
        String name = unitPriceStrategyAddRequest.getName();
        Integer applyType = unitPriceStrategyAddRequest.getApplyType();
        List<Long> commodityUnitPriceIdList = unitPriceStrategyAddRequest.getMemberUnitPriceList().stream().map(commodityMemberUnitPriceRequest -> commodityMemberUnitPriceRequest.getCommodityUnitPrice().getId()).collect(Collectors.toList());
        Boolean isEnable = true;
        Boolean flag;
        //判断参数是否为空
        List<CommodityMemberUnitPriceRequest> commodityMemberUnitPriceList = unitPriceStrategyAddRequest.getMemberUnitPriceList();
        if (commodityMemberUnitPriceList == null || commodityMemberUnitPriceList.isEmpty()) {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_UNITPRICE_NOT_EXIST);
        }

        //判断是商城维度还是会员维度
        boolean isMember;
        List<CommodityMemberRequest> commodityMemberRequestList = new ArrayList<>();
        List<CommodityMemberLevelRequest> commodityMemberLevelRequestList = new ArrayList<>();
        if(UnitPriceStrategyApplyTypeEnum.Member.getCode().equals(applyType)){
            commodityMemberRequestList = unitPriceStrategyAddRequest.getCommodityMemberList();
            isMember = !CollectionUtils.isEmpty(commodityMemberRequestList);
        }else{
            commodityMemberLevelRequestList = unitPriceStrategyAddRequest.getCommodityMemberLevelList();
            isMember = !CollectionUtils.isEmpty(commodityMemberLevelRequestList);
        }
        //判断是新增还是修改
        if (id != null && id > 0) {
            CommodityUnitPriceStrategy unitPriceStrategy = commodityUnitPriceStrategyRepository.findById(id).orElse(null);
            if (unitPriceStrategy != null) {
                isEnable = unitPriceStrategy.getIsEnable();
                boolean exists;
                if (!isMember) {
                    //判断该商品在此商城下是否存在了会员/会员等级价格策略
                    exists = commodityUnitPriceStrategyRepository.existsByIdNotAndShopIdAndMemberUnitPriceListCommodityUnitPriceIdInAndIsMember(id, shopId, commodityUnitPriceIdList, false);
                }else{
                    //判断该商品是否存在了跟applyType相同的适用类型价格策略
                    if(UnitPriceStrategyApplyTypeEnum.Member.getCode().equals(applyType)){
                        List<Long> memberIdList = new ArrayList<>();
                        List<Long> memberRoleIdList = new ArrayList<>();
                        commodityMemberRequestList.forEach(commodityMemberRequest -> {
                            memberIdList.add(commodityMemberRequest.getMemberId());
                            memberRoleIdList.add(commodityMemberRequest.getMemberRoleId());
                        });
                        exists = commodityUnitPriceStrategyRepository.existsByIdNotAndShopIdAndMemberUnitPriceListCommodityUnitPriceIdInAndIsMemberAndApplyTypeAndCommodityMemberListMemberIdInAndCommodityMemberListMemberRoleIdIn(id, shopId, commodityUnitPriceIdList, true, applyType, memberIdList, memberRoleIdList);
                    }else{
                        List<Integer> memberLevelList = new ArrayList<>();
                        List<Long> memberRoleIdList = new ArrayList<>();
                        commodityMemberLevelRequestList.forEach(commodityMemberLevelRequest -> {
                            memberLevelList.add(commodityMemberLevelRequest.getLevel());
                            memberRoleIdList.add(commodityMemberLevelRequest.getMemberRoleId());
                        });
                        exists = commodityUnitPriceStrategyRepository.existsByIdNotAndShopIdAndMemberUnitPriceListCommodityUnitPriceIdInAndIsMemberAndApplyTypeAndCommodityMemberLevelListLevelInAndCommodityMemberLevelListMemberRoleIdIn(id, shopId, commodityUnitPriceIdList, true, applyType, memberLevelList, memberRoleIdList);
                    }
                }
                if (exists) {
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_SHOP_UNITPRICE_STRATEGY_EXIST);
                }
            } else {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_UNITPRICE_STRATEGY_NOT_EXIST);
            }
            flag = commodityUnitPriceStrategyRepository.existsByNameAndIdNotAndMemberIdAndMemberRoleId(name, id, memberId, memberRoleId);
            //清除会员中间表
            commodityMemberRepository.deleteByCommodityUnitPriceStrategyId(id);
            commodityMemberLevelRepository.deleteByCommodityUnitPriceStrategyId(id);
            commodityMemberUnitPriceRepository.deleteByCommodityUnitPriceStrategyId(id);
        } else {
            flag = commodityUnitPriceStrategyRepository.existsByNameAndMemberIdAndMemberRoleId(name, memberId, memberRoleId);
            boolean exists;
            if (!isMember) {
                //判断该商品在此商城下是否存在了会员/会员等级价格策略
                exists = commodityUnitPriceStrategyRepository.existsByShopIdAndMemberUnitPriceListCommodityUnitPriceIdInAndIsMember(shopId, commodityUnitPriceIdList, false);
            }else{
                //判断该商品是否存在了跟applyType相同的适用类型价格策略
                if(UnitPriceStrategyApplyTypeEnum.Member.getCode().equals(applyType)){
                    List<Long> memberIdList = new ArrayList<>();
                    List<Long> memberRoleIdList = new ArrayList<>();
                    commodityMemberRequestList.forEach(commodityMemberRequest -> {
                        memberIdList.add(commodityMemberRequest.getMemberId());
                        memberRoleIdList.add(commodityMemberRequest.getMemberRoleId());
                    });
                    exists = commodityUnitPriceStrategyRepository.existsByShopIdAndMemberUnitPriceListCommodityUnitPriceIdInAndIsMemberAndApplyTypeAndCommodityMemberListMemberIdInAndCommodityMemberListMemberRoleIdIn(shopId, commodityUnitPriceIdList, true, applyType, memberIdList, memberRoleIdList);
                }else{
                    List<Integer> memberLevelList = new ArrayList<>();
                    List<Long> memberRoleIdList = new ArrayList<>();
                    commodityMemberLevelRequestList.forEach(commodityMemberLevelRequest -> {
                        memberLevelList.add(commodityMemberLevelRequest.getLevel());
                        memberRoleIdList.add(commodityMemberLevelRequest.getMemberRoleId());
                    });
                    exists = commodityUnitPriceStrategyRepository.existsByShopIdAndMemberUnitPriceListCommodityUnitPriceIdInAndIsMemberAndApplyTypeAndCommodityMemberLevelListLevelInAndCommodityMemberLevelListMemberRoleIdIn(shopId, commodityUnitPriceIdList, true, applyType, memberLevelList, memberRoleIdList);
                }
            }
            if (exists) {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_SHOP_UNITPRICE_STRATEGY_EXIST);
            }
        }
        //判断名称是否重复
        if (!flag) {
            //获取参数
            Integer type = unitPriceStrategyAddRequest.getType();
            Integer environment = unitPriceStrategyAddRequest.getEnvironment();
            Integer priceType = unitPriceStrategyAddRequest.getPriceType();
            //判断关联商品是否存在
            SimpleIdRequest commodityRequest = unitPriceStrategyAddRequest.getCommodity();
            Long commodityId = commodityRequest.getId();
            Commodity commodity = commodityRepository.findById(commodityId).orElse(null);
            if (commodity != null) {
                CommodityUnitPriceStrategy unitPriceStrategy = new CommodityUnitPriceStrategy();
                unitPriceStrategy.setId(id);
                unitPriceStrategy.setName(name);
                unitPriceStrategy.setCommodity(commodity);
                unitPriceStrategy.setShopId(shopId);
                unitPriceStrategy.setType(type);
                unitPriceStrategy.setEnvironment(environment);
                unitPriceStrategy.setIsEnable(isEnable);
                unitPriceStrategy.setMemberId(memberId);
                unitPriceStrategy.setMemberName(sysUser.getCompany());
                unitPriceStrategy.setMemberRoleId(memberRoleId);
                unitPriceStrategy.setMemberRoleName(sysUser.getMemberRoleName());
                unitPriceStrategy.setUserId(sysUser.getUserId());
                unitPriceStrategy.setUserName(sysUser.getUserName());
                unitPriceStrategy.setCreateTime(System.currentTimeMillis());
                unitPriceStrategy.setPriceType(priceType);
                unitPriceStrategy.setIsMember(isMember);
                unitPriceStrategy.setApplyType(applyType);
                //设置价格
                List<CommodityMemberUnitPrice> memberUnitPriceList = commodityMemberUnitPriceList.stream().map(commodityMemberUnitPriceRequest -> {
                    Map<String, Double> unitPrice = commodityMemberUnitPriceRequest.getUnitPrice();
                    Long commodityMemberUnitPriceRequestId = commodityMemberUnitPriceRequest.getId();
                    CommodityMemberUnitPrice commodityMemberUnitPrice;
                    if (commodityMemberUnitPriceRequestId != null && commodityMemberUnitPriceRequestId > 0) {
                        commodityMemberUnitPrice = commodityMemberUnitPriceRepository.findById(commodityMemberUnitPriceRequestId).orElse(null);
                        if (commodityMemberUnitPrice != null) {
                            commodityMemberUnitPrice.setUnitPrice(unitPrice);
                        } else {
                            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_UNITPRICE_NOT_EXIST);
                        }
                    } else {
                        SimpleIdRequest unitPriceAndPic = commodityMemberUnitPriceRequest.getCommodityUnitPrice();
                        if (unitPriceAndPic != null) {
                            Long unitPriceAndPicId = unitPriceAndPic.getId();
                            if (unitPriceAndPicId != null && unitPriceAndPicId > 0) {
                                CommodityUnitPriceAndPic commodityUnitPriceAndPic = commodityUnitPriceAndPicRepository.findById(unitPriceAndPicId).orElse(null);
                                if (commodityUnitPriceAndPic != null) {
                                    commodityMemberUnitPrice = new CommodityMemberUnitPrice();
                                    commodityMemberUnitPrice.setUnitPrice(unitPrice);
                                    commodityMemberUnitPrice.setCommodityUnitPrice(commodityUnitPriceAndPic);
                                    commodityMemberUnitPrice.setCommodityUnitPriceStrategy(unitPriceStrategy);
                                } else {
                                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_UNITPRICE_NOT_EXIST);
                                }
                            } else {
                                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_UNITPRICE_NOT_EXIST);
                            }
                        } else {
                            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_UNITPRICE_NOT_EXIST);
                        }
                    }
                    return commodityMemberUnitPrice;
                }).collect(Collectors.toList());
                unitPriceStrategy.setMemberUnitPriceList(memberUnitPriceList);

                //计算最大值和最小值
                List<Map<String, Double>> collect = commodityMemberUnitPriceList.stream().filter(unitPriceAndPic -> unitPriceAndPic != null && unitPriceAndPic.getUnitPrice() != null && unitPriceAndPic.getUnitPrice().size() > 0).map(CommodityMemberUnitPriceRequest::getUnitPrice).collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    Double min = Collections.min(collect.stream().map(m -> Collections.min(m.values())).collect(Collectors.toList()));
                    Double max = Collections.max(collect.stream().map(m -> Collections.max(m.values())).collect(Collectors.toList()));
                    unitPriceStrategy.setMin(min);
                    unitPriceStrategy.setMax(max);
                } else {
                    unitPriceStrategy.setMin(0d);
                    unitPriceStrategy.setMax(0d);
                }

                //判断适用维度
                if(UnitPriceStrategyApplyTypeEnum.Member.getCode().equals(applyType)){
                    //适用会员
                    if (!CollectionUtils.isEmpty(commodityMemberRequestList)) {
                        List<CommodityMember> commodityMemberList = commodityMemberRequestList.stream().map(commodityMemberRequest -> {
                            CommodityMember commodityMember = new CommodityMember();
                            commodityMember.setMemberId(commodityMemberRequest.getMemberId());
                            commodityMember.setMemberName(commodityMemberRequest.getMemberName());
                            commodityMember.setMemberRoleId(commodityMemberRequest.getMemberRoleId());
                            commodityMember.setMemberRoleName(commodityMemberRequest.getMemberRoleName());
                            commodityMember.setMemberTypeName(commodityMemberRequest.getMemberTypeName());
                            commodityMember.setCommodityUnitPriceStrategy(unitPriceStrategy);
                            return commodityMember;
                        }).collect(Collectors.toList());
                        unitPriceStrategy.setCommodityMemberList(commodityMemberList);
                    }
                }else{
                    //适用会员等级
                    if (!CollectionUtils.isEmpty(commodityMemberLevelRequestList)) {
                        List<CommodityMemberLevel> commodityMemberLevelList = commodityMemberLevelRequestList.stream().map(commodityMemberLevelRequest -> {
                            CommodityMemberLevel commodityMemberLevel = new CommodityMemberLevel();
                            commodityMemberLevel.setMemberRoleId(commodityMemberLevelRequest.getMemberRoleId());
                            commodityMemberLevel.setMemberRoleName(commodityMemberLevelRequest.getMemberRoleName());
                            commodityMemberLevel.setMemberType(commodityMemberLevelRequest.getMemberType());
                            commodityMemberLevel.setMemberTypeName(commodityMemberLevelRequest.getMemberTypeName());
                            commodityMemberLevel.setLevel(commodityMemberLevelRequest.getLevel());
                            commodityMemberLevel.setLevelTag(commodityMemberLevelRequest.getLevelTag());
                            commodityMemberLevel.setLevelType(commodityMemberLevelRequest.getLevelType());
                            commodityMemberLevel.setLevelTypeName(commodityMemberLevelRequest.getLevelTypeName());
                            commodityMemberLevel.setCommodityUnitPriceStrategy(unitPriceStrategy);
                            return commodityMemberLevel;
                        }).collect(Collectors.toList());
                        unitPriceStrategy.setCommodityMemberLevelList(commodityMemberLevelList);
                    }
                }

                //保存价格策略
                commodityUnitPriceStrategyRepository.saveAndFlush(unitPriceStrategy);
                //保存商品信息
                commodity.setIsUnitPriceStrategy(true);
                commodityRepository.saveAndFlush(commodity);

                //同步es中的数据
                syncEsCommodityService.updateUnitPriceStrategy(BeanUtil.copyProperties(unitPriceStrategy, UnitPriceStrategyResponse.class));

                return unitPriceStrategy.getId();
            } else {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
            }
        } else {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_UNITPRICE_STRATEGY_NAME_EXIST);
        }
    }

    /**
     * 查询价格策略--商品能力
     *
     * @param id 价格策略id
     * @return
     */
    @Override
    public CommodityUnitPriceStrategy getUnitPriceStrategy(Long id) {
        return commodityUnitPriceStrategyRepository.findById(id).orElse(null);
    }

    /**
     * 通过商品id获取价格策略的所有会员--商品能力
     *
     * @param commodityId 商品id
     * @return
     */
    @Override
    public List<CommodityMember> getStrategyMemberByCommodityId(Long commodityId) {
        return commodityMemberRepository.findByCommodityUnitPriceStrategyCommodityId(commodityId);
    }

    /**
     * 启用/停用价格策略--商品能力
     *
     * @return
     */
    @Transactional
    @Override
    public String updateUnitPriceStrategyStatus(UserLoginCacheDTO sysUser, Long id, Boolean isEnable) {
        CommodityUnitPriceStrategy unitPriceStrategy = commodityUnitPriceStrategyRepository.findById(id).orElse(null);
        if (unitPriceStrategy != null) {
            //更新价格策略
            unitPriceStrategy.setIsEnable(isEnable);
            commodityUnitPriceStrategyRepository.saveAndFlush(unitPriceStrategy);
            //更新商品信息
            Commodity commodity = unitPriceStrategy.getCommodity();
            boolean flag = commodity.getUnitPriceStrategyList().stream().anyMatch(CommodityUnitPriceStrategy::getIsEnable);
            commodity.setIsUnitPriceStrategy(flag);
            commodityRepository.saveAndFlush(commodity);
            //同步es中的数据
            syncEsCommodityService.updateUnitPriceStrategy(BeanUtil.copyProperties(unitPriceStrategy, UnitPriceStrategyResponse.class));
            return ResponseCode.SUCCESS.getMessage();
        } else {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_UNITPRICE_STRATEGY_NOT_EXIST);
        }
    }

    /**
     * 删除价格策略--商品能力
     *
     * @param id 价格策略id
     * @return
     */
    @Override
    public String deleteUnitPriceStrategy(Long id) {
        CommodityUnitPriceStrategy unitPriceStrategy = commodityUnitPriceStrategyRepository.findById(id).orElse(null);
        if (unitPriceStrategy != null) {
            Boolean isEnable = unitPriceStrategy.getIsEnable();
            if (isEnable) {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_UNITPRICE_STATUS_NOT_DELETE);
            } else {
                commodityUnitPriceStrategyRepository.deleteById(id);
                //更新商品信息
                Commodity commodity = unitPriceStrategy.getCommodity();
                boolean flag = commodity.getUnitPriceStrategyList().stream().anyMatch(CommodityUnitPriceStrategy::getIsEnable);
                commodity.setIsUnitPriceStrategy(flag);
                commodityRepository.saveAndFlush(commodity);
                return ResponseCode.SUCCESS.getMessage();
            }
        } else {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_UNITPRICE_STRATEGY_NOT_EXIST);
        }
    }

    /**
     * 判断商品是否上架
     *
     * @return
     */
    @Override
    public String getCommodityIsPublish(Long shopId, List<CommodityNameRequest> commodityNameList) {
        List<Long> commodityIdList = commodityNameList.stream().map(CommodityNameRequest::getCommodityId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
        List<CommodityShop> commodityShopList = commodityShopRepository.findByCommodityIdInAndShopId(commodityIdList, shopId);
        //判断是否存在未上架的商品
        if (commodityIdList.size() != commodityShopList.size()) {
            List<Long> onLineProductIdList = commodityShopList.stream().map(item -> item.getCommodity().getId()).collect(Collectors.toList());
            List<Long> offLineProductIdList = commodityIdList.stream().filter(item -> !onLineProductIdList.contains(item)).collect(Collectors.toList());
            if (offLineProductIdList.size() > 0) {
                //获取未上架的所有商品名称，通过逗号隔开
                String commodityName = commodityNameList.stream().filter(item -> offLineProductIdList.contains(item.getCommodityId())).map(CommodityNameRequest::getCommodityName).collect(Collectors.joining(","));
                return "商品：" + commodityName + " 已下架";
            }
        }
        return null;
    }

    /**
     * 判断商品是否上架
     *
     * @return
     */
    @Override
    public List<Long> getCommodityListByIsPublish(Long shopId, List<CommodityNameRequest> commodityNameList) {
        List<Long> commodityIdList = commodityNameList.stream().map(CommodityNameRequest::getCommodityId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
        List<CommodityShop> commodityShopList = commodityShopRepository.findByCommodityIdInAndShopId(commodityIdList, shopId);
        //判断是否存在未上架的商品
        if (commodityIdList.size() != commodityShopList.size()) {
            return commodityShopList.stream().map(item -> item.getCommodity().getId()).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 查询商品信息列表--订单校验商品信息
     *
     * @param commodityPriceRequest 查询条件实体
     * @return
     */
    @Override
    public List<CommodityOrderResponse> getCommodityListByOrder(CommodityPriceRequest commodityPriceRequest) {
        Long shopId = commodityPriceRequest.getShopId();
        Long loginMemberId = commodityPriceRequest.getMemberId();
        Long loginMemberRoleId = commodityPriceRequest.getMemberRoleId();
        List<Long> commoditySkuIdList = commodityPriceRequest.getCommoditySkuIdList();

        //查询登录用户的所有上级对应的会员等级
        Map<String, Integer> memberLevelMap = new HashMap<>();
        MemberFeignVO memberFeignVO = new MemberFeignVO();
        memberFeignVO.setMemberId(loginMemberId);
        memberFeignVO.setRoleId(loginMemberRoleId);
        Wrapper<List<MemberFeignLevelDetailVO>> subMemberLevels = memberLevelRightCreditControllerFeign.findSubMemberLevels(memberFeignVO);
        if(subMemberLevels != null && ResponseCode.SUCCESS.getCode() == subMemberLevels.getCode()){
            List<MemberFeignLevelDetailVO> data = subMemberLevels.getData();
            if(!CollectionUtils.isEmpty(data)){
                data.stream().filter(memberFeignLevelDetailVO -> memberFeignLevelDetailVO.getRelType() == 1).forEach(memberFeignLevelDetailVO -> {
                    Long upperMemberId = memberFeignLevelDetailVO.getUpperMemberId();
                    Long upperRoleId = memberFeignLevelDetailVO.getUpperRoleId();
                    Integer level = memberFeignLevelDetailVO.getLevel();
                    memberLevelMap.put(upperMemberId + Constants.UNDERLINE_STR + upperRoleId, level);
                });
            }
        }

        List<CommodityOrderResponse> commodityOrderResponseList = new ArrayList<>();
        List<CommodityUnitPriceAndPic> commodityUnitPriceAndPicList = commodityUnitPriceAndPicRepository.findByIdIn(commoditySkuIdList);
        if (commodityUnitPriceAndPicList != null && !commodityUnitPriceAndPicList.isEmpty()) {
            for (CommodityUnitPriceAndPic commodityUnitPriceAndPic : commodityUnitPriceAndPicList) {
                Long commodityUnitPriceAndPicId = commodityUnitPriceAndPic.getId();
                Commodity commodity = commodityUnitPriceAndPic.getCommodity();
                CommodityOrderResponse commodityOrderResponse = new CommodityOrderResponse();
                commodityOrderResponse.setCommodityId(commodity.getId());
                commodityOrderResponse.setId(commodityUnitPriceAndPicId);
                commodityOrderResponse.setCode(Constants.COMMODITY_CODE_PREFIX + CodeUtils.digits32(commodityUnitPriceAndPic.getId(), Constants.CODE_NUM));
                commodityOrderResponse.setUnitName(commodity.getUnitName());
                commodityOrderResponse.setPriceType(commodity.getPriceType());
                commodityOrderResponse.setCustomerCategoryName(commodity.getCustomerCategory().getName());
                if (commodity.getBrand() != null) {
                    commodityOrderResponse.setBrandName(commodity.getBrand().getName());
                }

                //设置商品默认价格
                Map<String, Double> unitPrice = commodityUnitPriceAndPic.getUnitPrice();
                if (unitPrice != null && unitPrice.size() > 0) {
                    commodityOrderResponse.setMin(Collections.min(unitPrice.values()));
                    commodityOrderResponse.setMax(Collections.max(unitPrice.values()));
                    commodityOrderResponse.setUnitPrice(unitPrice);
                }
                //根据价格策略设置价格
                List<CommodityUnitPriceStrategy> unitPriceStrategyList = commodityUnitPriceAndPic.getCommodity().getUnitPriceStrategyList();
                List<CommodityUnitPriceStrategy> shopPriceStrategy = unitPriceStrategyList.stream().filter(unitPriceStrategy -> unitPriceStrategy.getShopId().equals(shopId) && unitPriceStrategy.getIsEnable() && !unitPriceStrategy.getIsMember()).collect(Collectors.toList());
                List<CommodityUnitPriceStrategy> memberPriceStrategy = unitPriceStrategyList.stream().filter(unitPriceStrategy -> unitPriceStrategy.getShopId().equals(shopId) && unitPriceStrategy.getIsEnable() && unitPriceStrategy.getIsMember()).collect(Collectors.toList());
                boolean flag = true;
                //根据价格策略的会员来设置价格
                for (CommodityUnitPriceStrategy commodityUnitPriceStrategy : memberPriceStrategy) {
                    List<CommodityMemberUnitPrice> memberUnitPriceList = commodityUnitPriceStrategy.getMemberUnitPriceList();
                    Integer applyType = commodityUnitPriceStrategy.getApplyType();
                    if(UnitPriceStrategyApplyTypeEnum.Member.getCode().equals(applyType)){
                        List<CommodityMember> commodityMemberList = commodityUnitPriceStrategy.getCommodityMemberList();
                        for (CommodityMember commodityMember : commodityMemberList) {
                            Long memberId = commodityMember.getMemberId();
                            Long memberRoleId = commodityMember.getMemberRoleId();
                            if (memberId.equals(loginMemberId) && memberRoleId.equals(loginMemberRoleId)) {
                                for (CommodityMemberUnitPrice commodityMemberUnitPrice : memberUnitPriceList) {
                                    CommodityUnitPriceAndPic commodityUnitPrice = commodityMemberUnitPrice.getCommodityUnitPrice();
                                    if (commodityUnitPrice.getId().equals(commodityUnitPriceAndPicId)) {
                                        Map<String, Double> memberUnitPrice = commodityMemberUnitPrice.getUnitPrice();
                                        commodityOrderResponse.setMin(commodityUnitPriceStrategy.getMin());
                                        commodityOrderResponse.setMax(commodityUnitPriceStrategy.getMax());
                                        commodityOrderResponse.setUnitPrice(memberUnitPrice);
                                        flag = false;
                                    }
                                }
                            }
                        }
                    }else{
                        List<CommodityMemberLevel> commodityMemberLevelList = commodityUnitPriceStrategy.getCommodityMemberLevelList();
                        for (CommodityMemberLevel commodityMemberLevel : commodityMemberLevelList) {
                            Long memberRoleId = commodityMemberLevel.getMemberRoleId();
                            Integer level = commodityMemberLevel.getLevel();
                            Integer loginMemberLevel = memberLevelMap.get(commodity.getMemberId() + Constants.UNDERLINE_STR + commodity.getMemberRoleId());
                            if (memberRoleId.equals(loginMemberRoleId) && level.equals(loginMemberLevel == null ? 0 : loginMemberLevel)) {
                                for (CommodityMemberUnitPrice commodityMemberUnitPrice : memberUnitPriceList) {
                                    CommodityUnitPriceAndPic commodityUnitPrice = commodityMemberUnitPrice.getCommodityUnitPrice();
                                    if (commodityUnitPrice.getId().equals(commodityUnitPriceAndPicId)) {
                                        Map<String, Double> memberUnitPrice = commodityMemberUnitPrice.getUnitPrice();
                                        commodityOrderResponse.setMin(commodityUnitPriceStrategy.getMin());
                                        commodityOrderResponse.setMax(commodityUnitPriceStrategy.getMax());
                                        commodityOrderResponse.setUnitPrice(memberUnitPrice);
                                        flag = false;
                                    }
                                }
                            }
                        }
                    }
                }
                if (flag) {
                    //根据价格策略的商城来设置价格
                    shopPriceStrategy.forEach(commodityUnitPriceStrategy -> {
                        List<CommodityMemberUnitPrice> memberUnitPriceList = commodityUnitPriceStrategy.getMemberUnitPriceList();
                        memberUnitPriceList.forEach(commodityMemberUnitPrice -> {
                            CommodityUnitPriceAndPic commodityUnitPrice = commodityMemberUnitPrice.getCommodityUnitPrice();
                            if (commodityUnitPrice.getId().equals(commodityUnitPriceAndPicId)) {
                                Map<String, Double> memberUnitPrice = commodityMemberUnitPrice.getUnitPrice();
                                commodityOrderResponse.setMin(commodityUnitPriceStrategy.getMin());
                                commodityOrderResponse.setMax(commodityUnitPriceStrategy.getMax());
                                commodityOrderResponse.setUnitPrice(memberUnitPrice);
                            }
                        });
                    });
                }
                //商品属性
                List<CommodityGoodsAttribute> attributeAndValueList = commodityUnitPriceAndPic.getAttributeAndValueList();
                String attribute = StringUtils.join(attributeAndValueList.stream().sorted(Comparator.comparing(CommodityGoodsAttribute::getId).reversed()).map(commodityGoodsAttribute -> commodityGoodsAttribute.getCustomerAttributeValue().getValue()).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR);
                if (StringUtils.isNotEmpty(attribute)) {
                    commodityOrderResponse.setAttribute(attribute);
                }
                //商品类型
                Integer type = commodity.getType();
                commodityOrderResponse.setType(type);
                //上游商品才有值
                if (CommodityTypeEnum.Upper.getCode().equals(type)) {
                    commodityOrderResponse.setCommodityUnitPriceAndPicId(commodityUnitPriceAndPic.getUpperCommoditySkuId());
                    commodityOrderResponse.setUpperMemberId(commodity.getUpperMemberId());
                    commodityOrderResponse.setUpperMemberName(commodity.getUpperMemberName());
                    commodityOrderResponse.setUpperMemberRoleId(commodity.getUpperMemberRoleId());
                    commodityOrderResponse.setUpperMemberRoleName(commodity.getUpperMemberRoleName());
                }
                //物流信息
                LogisticsResponse logisticsResponse = new LogisticsResponse();
                BeanUtil.copyProperties(commodity.getLogistics(), logisticsResponse);
                commodityOrderResponse.setLogistics(logisticsResponse);
                //是否上架
                List<CommodityShop> commodityShopList = commodity.getCommodityShopList();
                if (commodityShopList != null && commodityShopList.size() > 0) {
                    List<Long> commodityShopIdList = commodityShopList.stream().map(CommodityShop::getShopId).collect(Collectors.toList());
                    if (commodityShopIdList.size() > 0 && commodityShopIdList.contains(shopId)) {
                        commodityOrderResponse.setIsPublish(true);
                    }
                }

                commodityOrderResponse.setName(commodity.getName());
                commodityOrderResponse.setIsMemberPrice(commodity.getIsMemberPrice());
                commodityOrderResponse.setMemberId(commodity.getMemberId());
                commodityOrderResponse.setMemberName(commodity.getMemberName());
                commodityOrderResponse.setMemberRoleId(commodity.getMemberRoleId());
                commodityOrderResponse.setMemberRoleName(commodity.getMemberRoleName());
                commodityOrderResponse.setMainPic(commodity.getMainPic());
                commodityOrderResponse.setMinOrder(commodity.getMinOrder());
                commodityOrderResponse.setTaxRate(commodity.getTaxRate());
                commodityOrderResponse.setIsCrossBorder(commodity.getIsCrossBorder());

                commodityOrderResponseList.add(commodityOrderResponse);
            }
        }
        return commodityOrderResponseList;
    }

    /**
     * 查询商品并通过商城id分组
     *
     * @param commodityIdList 商品id数组
     * @return key:商城id; value:商品id数组
     */
    @Override
    public Map<Long, List<Commodity>> getCommodityListGroupByShopId(List<Long> commodityIdList) {
        List<Commodity> commodityList = commodityRepository.findAllById(commodityIdList);
        if (commodityList.size() > 0 && commodityIdList.size() == commodityList.size()) {
            Map<Long, List<Commodity>> map = new HashMap<>();
            commodityList.forEach(commodity -> {
                List<CommodityShop> commodityShopList = commodity.getCommodityShopList();
                commodityShopList.forEach(commodityShop -> {
                    Long shopId = commodityShop.getShopId();
                    List<Commodity> shopIdCommodityList = map.get(shopId);
                    if (shopIdCommodityList != null && shopIdCommodityList.size() > 0) {
                        if (!shopIdCommodityList.contains(commodity)) {
                            shopIdCommodityList.add(commodity);
                        }
                    } else {
                        shopIdCommodityList = new ArrayList<>();
                        shopIdCommodityList.add(commodity);
                    }
                    map.put(shopId, shopIdCommodityList);
                });
            });
            if (map.size() > 0) {
                return map;
            } else {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_PUBLISH);
            }
        }
        throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
    }

    /**
     * 通过商品skuId数组查询对应的商品一级品类id
     *
     * @param commoditySkuIdList 商品skuId数组
     */
    @Override
    public List<CommoditySkuIdAndFirstCategoryIdResponse> getCommodityFirstCategoryIdList(List<Long> commoditySkuIdList) {
        List<CommodityUnitPriceAndPic> commodityUnitPriceAndPicList = commodityUnitPriceAndPicRepository.findByIdIn(commoditySkuIdList);
        return commodityUnitPriceAndPicList.stream().map(commodityUnitPriceAndPic -> {
            Commodity commodity = commodityUnitPriceAndPic.getCommodity();
            CustomerCategory customerCategory = commodity.getCustomerCategory();
            String categoryId = customerCategory.getFullId();
            if (categoryId.contains(".")) {
                categoryId = categoryId.substring(0, categoryId.indexOf("."));
            }

            CommoditySkuIdAndFirstCategoryIdResponse response = new CommoditySkuIdAndFirstCategoryIdResponse();
            response.setCommoditySkuId(commodityUnitPriceAndPic.getId());
            response.setCategoryId(Long.valueOf(categoryId));
            return response;
        }).collect(Collectors.toList());
    }

    /**
     * 通过商品id查询对应的商品skuId数组
     *
     * @param idList 商品id数组
     */
    @Override
    public List<CommodityIdAndSkuIdListResponse> getCommoditySkuIdList(List<Long> idList) {
        List<Commodity> commodityList = commodityRepository.findAllById(idList);
        return commodityList.stream().map(commodity -> {
            List<CommodityUnitPriceAndPic> unitPriceAndPicList = commodity.getUnitPriceAndPicList();
            List<Long> commoditySkuIdList = unitPriceAndPicList.stream().map(CommodityUnitPriceAndPic::getId).collect(Collectors.toList());
            CommodityIdAndSkuIdListResponse commodityIdAndSkuIdListResponse = new CommodityIdAndSkuIdListResponse();
            commodityIdAndSkuIdListResponse.setCommodityId(commodity.getId());
            commodityIdAndSkuIdListResponse.setSkuIdList(commoditySkuIdList);
            return commodityIdAndSkuIdListResponse;
        }).collect(Collectors.toList());
    }

    /**
     * 查询商品是否配置了库存
     *
     * @param commodityIdList 商品Id数组
     * @return 返回没有配置库存的商品id数组
     */
    @Override
    public List<Long> getCommodityIsExistStock(List<Long> commodityIdList) {
        List<String> keysList = new ArrayList<>();
        Map<Long, Long> commoditySkuIdAndIdMap = new HashMap<>();
        List<Commodity> commodityList = commodityRepository.findAllById(commodityIdList);
        if (commodityList.size() > 0) {
            commodityList.forEach(commodity -> {
                List<CommodityUnitPriceAndPic> unitPriceAndPicList = commodity.getUnitPriceAndPicList();
                unitPriceAndPicList.forEach(commodityUnitPriceAndPic -> {
                    Long skuId = commodityUnitPriceAndPic.getId();
                    commoditySkuIdAndIdMap.put(skuId, commodity.getId());
                    //拼接redisKey
                    String redisKey = CommonConstant.FREIGHT_SPACE_REDIS_KEY + "*_" + skuId;
                    keysList.add(redisKey);
                });
            });
            //查询redis中已经设置了库存的所有skuId
            List<Object> objects = redisStringUtils.searchKeyList(keysList, Constants.REDIS_PRODUCT_INDEX);
            List<Long> existCommoditySkuIdList = objects.stream().map(obj -> {
                if (obj != null) {
                    String value = String.valueOf(obj);
                    if (!"[]".equals(value)) {
                        String skuId = value.substring(value.lastIndexOf("_") + 1, value.lastIndexOf("]"));
                        return Long.valueOf(skuId);
                    }
                }
                return null;
            }).filter(Objects::nonNull).collect(Collectors.toList());
            //存在库存的商品去掉
            existCommoditySkuIdList.forEach(commoditySkuId -> {
                Long commodityId = commoditySkuIdAndIdMap.get(commoditySkuId);
                if (commodityId != null) {
                    commodityIdList.remove(commodityId);
                }
            });
            return commodityIdList;
        } else {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
        }
    }

    /**
     * S2B功能--商品列表 查看上游商品
     * 下游销售会员(B端)查看上游供应会员(S端)商品列表
     *
     * @param user                       登录会员信息
     * @param pageVO                     分页参数
     * @param commodityUpperQueryRequest 查询参数
     * @param modelMapper                对象转换类
     * @return 商品分页列表
     */
    @Override
    public Wrapper<PageData<S2BCommodityResponse>> getUpperCommodityListS2B(UserLoginCacheDTO user, PageVO pageVO, CommodityUpperQueryRequest commodityUpperQueryRequest, ModelMapper modelMapper) {
        //仅限服务提供者使用
        if (!RoleTypeEnum.SERVICE_PROVIDER.getCode().equals(user.getMemberRoleType())) {
            return Wrapper.fail(ResponseCode.ROLE_TYPE_NOT_SERVICE_PROVIDER_NO_SEE_UPPER);
        }
        //从缓存获取所有上游供应商信息(同时筛选角色为服务提供者的下级会员)
        List<MemberAndRoleIdDTO> upperVendorMembers;
        List<MemberAndRoleIdDTO> subVendorMembers = user.getSubVendorMembers();
        if (CollectionUtils.isEmpty(subVendorMembers)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        Wrapper<List<MemberAndRoleIdDTO>> result = memberInnerControllerFeign.screenMemberUser(subVendorMembers);
        upperVendorMembers = result.getData();
        if (ResponseCode.SUCCESS.getCode() != result.getCode()) {
            return Wrapper.fail(result.getMessage());
        }
        if (CollectionUtils.isEmpty(upperVendorMembers)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        //查询参数组装
        CommodityQueryRequest commodityQueryRequest = new CommodityQueryRequest();
        //会员信息
        commodityQueryRequest.setParentMemberIdList(upperVendorMembers.stream().map(MemberAndRoleIdDTO::getMemberId).collect(Collectors.toList()));
        commodityQueryRequest.setParentMemberRoleIds(upperVendorMembers.stream().map(MemberAndRoleIdDTO::getRoleId).collect(Collectors.toList()));
        //价格类型
        Integer priceType = commodityUpperQueryRequest.getPriceType();
        if (Objects.isNull(priceType)) {
            commodityQueryRequest.setPriceTypeList(Arrays.asList(PriceTypeEnum.Cash.getCode(), PriceTypeEnum.Consult.getCode()));
        } else {
            commodityQueryRequest.setPriceTypeList(Arrays.asList(priceType));
        }
        //状态为 审核通过、已上架、已下架
        commodityQueryRequest.setStatusList(Arrays.asList(CommodityStatusEnum.Pass.getCode(), CommodityStatusEnum.On_Shelf.getCode(), CommodityStatusEnum.Off_Shelf.getCode()));
        //商品类型为上游供应商品
        commodityQueryRequest.setCommodityType(CommodityTypeEnum.Upper.getCode());
        //其他查询参数
        commodityQueryRequest.setProductId(commodityUpperQueryRequest.getProductId());
        commodityQueryRequest.setName(commodityUpperQueryRequest.getName());
        commodityQueryRequest.setCustomerCategoryName(commodityUpperQueryRequest.getCustomerCategoryName());
        commodityQueryRequest.setBrandName(commodityUpperQueryRequest.getBrandName());
        commodityQueryRequest.setMemberName(commodityUpperQueryRequest.getMemberName());

        Page<Commodity> page = getCommodityList(pageVO, commodityQueryRequest);
        List<S2BCommodityResponse> resultList = modelMapper.map(page.getContent(), new TypeToken<List<S2BCommodityResponse>>() {
        }.getType());
        return Wrapper.success(new PageData<>(page.getTotalElements(), resultList));
    }

    /**
     * S2B功能--商品列表 查看下游商品
     * 上游供应会员(S端)查看下游销售会员(B端)商品列表
     *
     * @param user                       登录会员信息
     * @param pageVO                     分页参数
     * @param commodityUpperQueryRequest 查询参数(选择下游销售商品)
     * @param modelMapper                对象转换类
     * @return 商品分页列表
     */
    @Override
    public Wrapper<PageData<SubCommodityResponse>> getSubiteCommodityListS2B(UserLoginCacheDTO user, PageVO pageVO, CommodityUpperQueryRequest commodityUpperQueryRequest, ModelMapper modelMapper) {
        //仅限服务提供者使用
        if (!RoleTypeEnum.SERVICE_PROVIDER.getCode().equals(user.getMemberRoleType())) {
            return Wrapper.fail(ResponseCode.ROLE_TYPE_NOT_SERVICE_PROVIDER_NO_SEE_SUB);
        }
        //从缓存获取所有下游销售会员信息(同时筛选角色为服务提供者的上级会员)
        List<MemberAndRoleIdDTO> upperVendorMembers = user.getUpperVendorMembers();
        if (CollectionUtils.isEmpty(upperVendorMembers)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        Wrapper<List<MemberAndRoleIdDTO>> result = memberInnerControllerFeign.screenMemberUser(upperVendorMembers);
        upperVendorMembers = result.getData();
        if (ResponseCode.SUCCESS.getCode() != result.getCode()) {
            return Wrapper.fail(result.getMessage());
        }
        if (CollectionUtils.isEmpty(upperVendorMembers)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        //查询参数组装
        CommodityQueryRequest commodityQueryRequest = new CommodityQueryRequest();
        //会员信息
        commodityQueryRequest.setParentMemberIdList(upperVendorMembers.stream().map(MemberAndRoleIdDTO::getMemberId).collect(Collectors.toList()));
        commodityQueryRequest.setParentMemberRoleIds(upperVendorMembers.stream().map(MemberAndRoleIdDTO::getRoleId).collect(Collectors.toList()));
        //价格类型
        Integer priceType = commodityUpperQueryRequest.getPriceType();
        if (Objects.isNull(priceType)) {
            commodityQueryRequest.setPriceTypeList(Arrays.asList(PriceTypeEnum.Cash.getCode(), PriceTypeEnum.Consult.getCode()));
        } else {
            commodityQueryRequest.setPriceTypeList(Arrays.asList(priceType));
        }
        //状态为 审核通过、已上架、已下架
        commodityQueryRequest.setStatusList(Arrays.asList(CommodityStatusEnum.Pass.getCode(), CommodityStatusEnum.On_Shelf.getCode(), CommodityStatusEnum.Off_Shelf.getCode()));
        //商品类型为上游供应商品
        commodityQueryRequest.setCommodityType(CommodityTypeEnum.Upper.getCode());
        //其他查询参数
        commodityQueryRequest.setProductId(commodityUpperQueryRequest.getProductId());
        commodityQueryRequest.setName(commodityUpperQueryRequest.getName());
        commodityQueryRequest.setCustomerCategoryName(commodityUpperQueryRequest.getCustomerCategoryName());
        commodityQueryRequest.setBrandName(commodityUpperQueryRequest.getBrandName());
        commodityQueryRequest.setMemberName(commodityUpperQueryRequest.getMemberName());

        Page<Commodity> page = getCommodityList(pageVO, commodityQueryRequest);
        List<SubCommodityResponse> resultList = modelMapper.map(page.getContent(), new TypeToken<List<SubCommodityResponse>>() {
        }.getType());
        return Wrapper.success(new PageData<>(page.getTotalElements(), resultList));
    }

    /**
     * 判断货品是否于商品关联
     *
     * @param goodsIds 货品(物料)ids
     * @return Boolean
     */
    @Override
    public Boolean goodsUsing(SimpleIdListRequest goodsIds) {
        return commodityUnitPriceAndPicRepository.existsByGoodsIdIn(goodsIds.getIdList());
    }

    /**
     * 查询商品导入批次
     * @param importBath 商品导入批次
     */
    @Override
    public List<String> getCommodityImportBath(UserLoginCacheDTO sysUser, String importBath) {
        List<Commodity> commodityList;
        if(StringUtils.isNotEmpty(importBath)){
            commodityList = commodityRepository.findByMemberIdAndMemberRoleIdAndImportBatchContaining(sysUser.getMemberId(), sysUser.getMemberRoleId(), importBath);
        }else{
            commodityList = commodityRepository.findByMemberIdAndMemberRoleId(sysUser.getMemberId(), sysUser.getMemberRoleId());
        }
        if(!CollectionUtils.isEmpty(commodityList)){
            return commodityList.stream().map(Commodity::getImportBatch).filter(Objects::nonNull).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * 通过商品导入批次删除商品
     * @param importBath 商品导入批次
     */
    @Override
    public Boolean deleteCommodityByImportBath(UserLoginCacheDTO sysUser, String importBath) {
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        if(StringUtils.isNotEmpty(importBath)){
            List<Commodity> commodityList = commodityRepository.findByMemberIdAndMemberRoleIdAndImportBatch(sysUser.getMemberId(), sysUser.getMemberRoleId(), importBath);
            if(!CollectionUtils.isEmpty(commodityList)){
                //商品状态为待提交审核且从未提交过审核的商品才能删除
                long count = commodityList.stream().filter(commodity -> CommodityStatusEnum.Not_Submitted.getCode().equals(commodity.getStatus()) && commodity.getCheckTime() == null).count();
                if (commodityList.size() != count) {
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_IMPORT_BATH_NOT_DELETE);
                }
                //首页数据统计
                try {
                    List<OperateNoticeVO> operateNoticeVOList = new ArrayList<>();
                    //待提交审核商品
                    OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                    operateNoticeVO.setMemberId(memberId);
                    operateNoticeVO.setRoleId(memberRoleId);
                    operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                    operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_VALIFY_COMMIT.getCode());
                    operateNoticeVO.setReduceCount((long) commodityList.size());
                    operateNoticeVOList.add(operateNoticeVO);
                    //商品总数
                    operateNoticeVO = new OperateNoticeVO();
                    operateNoticeVO.setMemberId(memberId);
                    operateNoticeVO.setRoleId(memberRoleId);
                    operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                    operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.PRODUCT_COUNT.getCode());
                    operateNoticeVO.setReduceCount((long) commodityList.size());
                    operateNoticeVOList.add(operateNoticeVO);
                    reportControllerFeign.addOperateNoticeList(operateNoticeVOList);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                commodityRepository.deleteAll(commodityList);
                return true;
            }
        }
        throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_IMPORT_BATH_NOT_EXIST);
    }

    /**
     * 查询商品草稿列表
     * @param pageVO 分页实体
     * @return
     */
    @Override
    public PageData<CommodityDraftResponse> getCommodityDraftList(UserLoginCacheDTO sysUser, PageVO pageVO) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        Page<CommodityDraft> result = commodityDraftRepository.findByMemberIdAndMemberRoleIdOrderByIdDesc(memberId, memberRoleId, page);
        List<CommodityDraft> commodityDraftList = result.getContent();
        if(commodityDraftList.size() > 0){
            List<CommodityDraftResponse> commodityDraftResponseList = commodityDraftList.stream().map(commodityDraft -> {
                CommodityDraftResponse commodityDraftResponse = new CommodityDraftResponse();
                commodityDraftResponse.setId(commodityDraft.getId());
                commodityDraftResponse.setDraft(JSONUtil.parseObj(commodityDraft.getDraft()));
                return commodityDraftResponse;
            }).collect(Collectors.toList());
            return new PageData<>(result.getTotalElements(), commodityDraftResponseList);
        }
        return new PageData<>(0L, new ArrayList<>());
    }

    /**
     * 查询商品草稿
     * @param commodityDraftId 商品草稿id
     */
    @Override
    public CommodityDraftResponse getCommodityDraftById(Long commodityDraftId) {
        CommodityDraft commodityDraft = commodityDraftRepository.findById(commodityDraftId).orElse(null);
        if(commodityDraft != null){
            CommodityDraftResponse commodityDraftResponse = new CommodityDraftResponse();
            commodityDraftResponse.setId(commodityDraft.getId());
            commodityDraftResponse.setDraft(JSONUtil.parseObj(commodityDraft.getDraft()));
            return commodityDraftResponse;
        }
        throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_DRAFT_NOT_EXIST);
    }

    /**
     * 保存商品草稿
     */
    @Override
    public Long saveOrUpdateCommodityDraft(UserLoginCacheDTO sysUser, CommodityDraftRequest commodityDraftRequest) {
        Long id = commodityDraftRequest.getId();
        JSONObject draft = commodityDraftRequest.getDraft();
        if(id != null && id > 0){
            CommodityDraft commodityDraft = commodityDraftRepository.findById(id).orElse(null);
            if(commodityDraft != null){
                commodityDraft.setDraft(JSONUtil.toJsonStr(draft));
                commodityDraftRepository.saveAndFlush(commodityDraft);
                return commodityDraft.getId();
            }else{
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_DRAFT_NOT_EXIST);
            }
        }else{
            CommodityDraft commodityDraft = new CommodityDraft();
            commodityDraft.setMemberId(sysUser.getMemberId());
            commodityDraft.setMemberName(sysUser.getCompany());
            commodityDraft.setMemberRoleId(sysUser.getMemberRoleId());
            commodityDraft.setMemberRoleName(sysUser.getMemberRoleName());
            commodityDraft.setUserId(sysUser.getUserId());
            commodityDraft.setUserName(sysUser.getUserName());
            commodityDraft.setDraft(JSONUtil.toJsonStr(draft));
            commodityDraftRepository.saveAndFlush(commodityDraft);
            return commodityDraft.getId();
        }
    }

    /**
     * 删除商品草稿
     */
    @Override
    public Boolean deleteCommodityDraft(UserLoginCacheDTO sysUser, List<Long> commodityDraftIdList) {
        List<CommodityDraft> commodityDraftList = commodityDraftRepository.findByMemberIdAndMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), commodityDraftIdList);
        if(commodityDraftList.size() == commodityDraftIdList.size()){
            commodityDraftRepository.deleteInBatch(commodityDraftList);
            return true;
        }
        throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_DRAFT_NOT_EXIST);
    }

    /**
     * 导出商品导入模板
     * @return 导入模板
     */
    @Override
    public void exportCommodityTemplate(UserLoginCacheDTO sysUser, HttpServletRequest request, HttpServletResponse response) {
        //表格列名
        List<String> headerList = Arrays.stream(CommodityTemplateEnum.values()).map(CommodityTemplateEnum::getName).collect(Collectors.toList());

        //用于生成excel表格中的所有下拉框
        Map<Integer, List<String>> map = new HashMap<>();
        //用于生成excel表格中的所有级联关联
        List<ExcelReactData> reactDataMap = new ArrayList<>();

        //品类名称list，用于生成下拉框数据
        List<String> customerCategoryNameList = new ArrayList<>();
        //品类关联属性的对应关系
        Map<String, List<String>> customerCategoryAttributeMap = new HashMap<>();
        //属性关联属性值的对应关系
        Map<String, List<String>> customerAttributeMap = new HashMap<>();

        //从redis中查询所有品类信息，用于将fullId转成中文
        Map<String, String> customerCategoryRedisMap = redisStringUtils.hGetAll(Constants.REDIS_KEY_CUSTOMER_CATEGORY, Constants.REDIS_PRODUCT_INDEX);
        //查询当前会员的品类信息
        List<CustomerCategory> customerCategoryList = customerCategoryRepository.findByMemberIdAndMemberRoleId(sysUser.getMemberId(), sysUser.getMemberRoleId());
        customerCategoryList.forEach(customerCategory -> {
            String fullId = customerCategory.getFullId();
            String customerCategoryKey = "";
            //判断是否出现多级品类
            if(fullId.contains(Constants.SPLIT_STR_FULL_ID)){
                StringBuilder stringBuilder = new StringBuilder();
                String[] split = fullId.split(Constants.TRANSFER_STR + Constants.SPLIT_STR_FULL_ID);
                int customerCategoryId = Integer.parseInt(split[split.length - 1]);
                for (String s : split) {
                    String customerCategoryName = this.getCustomerCategoryName(Integer.parseInt(s), customerCategoryRedisMap);
                    if(StringUtils.isNotEmpty(customerCategoryName)){
                        stringBuilder.append(customerCategoryName).append(Constants.UNDERLINE_STR);
                    }
                }
                if(stringBuilder.length() > 0){
                    customerCategoryKey = stringBuilder + String.valueOf(customerCategoryId);
                    customerCategoryNameList.add(customerCategoryKey);
                }
            }else{
                int customerCategoryId = Integer.parseInt(fullId);
                String customerCategoryName = this.getCustomerCategoryName(customerCategoryId, customerCategoryRedisMap);
                if(StringUtils.isNotEmpty(customerCategoryName)){
                    customerCategoryKey = customerCategoryName + Constants.UNDERLINE_STR + customerCategoryId;
                    customerCategoryNameList.add(customerCategoryKey);
                }
            }
            //属性、属性值
            List<String> customerAttributeNameList = new ArrayList<>();
            List<CustomerAttribute> customerAttributeList = customerCategory.getCustomerAttributeList();
            customerAttributeList.forEach(customerAttribute -> {
                Long attributeId = customerAttribute.getId();
                Boolean isEnable = customerAttribute.getIsEnable();
                Boolean isPrice = customerAttribute.getIsPrice();
                Integer type = customerAttribute.getType();
                String attributeName = customerAttribute.getName();
                String attributeNameKey = attributeName + Constants.UNDERLINE_STR + attributeId;
                if(isEnable && isPrice && (type == 1 || type == 2)){
                    customerAttributeNameList.add(attributeNameKey);
                    List<CustomerAttributeValue> customerAttributeValueList = customerAttribute.getCustomerAttributeValueList();
                    List<String> customerAttributeValueNameList = new ArrayList<>();
                    customerAttributeValueList.stream().filter(CustomerAttributeValue::getIsEnable).forEach(customerAttributeValue -> {
                            customerAttributeValueNameList.add(customerAttributeValue.getValue() + Constants.UNDERLINE_STR + customerAttributeValue.getId());
                    });
                    //添加属性-属性值联动
                    if(!CollectionUtils.isEmpty(customerAttributeValueNameList)){
                        customerAttributeMap.put(attributeNameKey, customerAttributeValueNameList);
                    }
                }
            });
            //添加品类-属性联动
            if(!CollectionUtils.isEmpty(customerAttributeNameList)){
                customerCategoryAttributeMap.put(customerCategoryKey, customerAttributeNameList);
            }

        });
        //品类关联属性1
        ExcelReactData customerCategoryAttributeReactData1 = new ExcelReactData();
        customerCategoryAttributeReactData1.setKeyIndex(CommodityTemplateEnum.CustomerCategory.getCode());
        customerCategoryAttributeReactData1.setValueIndex(CommodityTemplateEnum.CommodityAttribute1.getCode());
        customerCategoryAttributeReactData1.setDataMap(customerCategoryAttributeMap);
        reactDataMap.add(customerCategoryAttributeReactData1);
        //品类关联属性2
        ExcelReactData customerCategoryAttributeReactData2 = new ExcelReactData();
        customerCategoryAttributeReactData2.setKeyIndex(CommodityTemplateEnum.CustomerCategory.getCode());
        customerCategoryAttributeReactData2.setValueIndex(CommodityTemplateEnum.CommodityAttribute2.getCode());
        customerCategoryAttributeReactData2.setDataMap(customerCategoryAttributeMap);
        reactDataMap.add(customerCategoryAttributeReactData2);
        //品类关联属性3
        ExcelReactData customerCategoryAttributeReactData3 = new ExcelReactData();
        customerCategoryAttributeReactData3.setKeyIndex(CommodityTemplateEnum.CustomerCategory.getCode());
        customerCategoryAttributeReactData3.setValueIndex(CommodityTemplateEnum.CommodityAttribute3.getCode());
        customerCategoryAttributeReactData3.setDataMap(customerCategoryAttributeMap);
        reactDataMap.add(customerCategoryAttributeReactData3);
        //品类关联属性4
        ExcelReactData customerCategoryAttributeReactData4 = new ExcelReactData();
        customerCategoryAttributeReactData4.setKeyIndex(CommodityTemplateEnum.CustomerCategory.getCode());
        customerCategoryAttributeReactData4.setValueIndex(CommodityTemplateEnum.CommodityAttribute4.getCode());
        customerCategoryAttributeReactData4.setDataMap(customerCategoryAttributeMap);
        reactDataMap.add(customerCategoryAttributeReactData4);
        //品类关联属性5
        ExcelReactData customerCategoryAttributeReactData5 = new ExcelReactData();
        customerCategoryAttributeReactData5.setKeyIndex(CommodityTemplateEnum.CustomerCategory.getCode());
        customerCategoryAttributeReactData5.setValueIndex(CommodityTemplateEnum.CommodityAttribute5.getCode());
        customerCategoryAttributeReactData5.setDataMap(customerCategoryAttributeMap);
        reactDataMap.add(customerCategoryAttributeReactData5);
        //属性1关联属性值1
        ExcelReactData customerAttributeReactData1 = new ExcelReactData();
        customerAttributeReactData1.setKeyIndex(CommodityTemplateEnum.CommodityAttribute1.getCode());
        customerAttributeReactData1.setValueIndex(CommodityTemplateEnum.CommodityAttributeValue1.getCode());
        customerAttributeReactData1.setDataMap(customerAttributeMap);
        reactDataMap.add(customerAttributeReactData1);
        //属性2关联属性值2
        ExcelReactData customerAttributeReactData2 = new ExcelReactData();
        customerAttributeReactData2.setKeyIndex(CommodityTemplateEnum.CommodityAttribute2.getCode());
        customerAttributeReactData2.setValueIndex(CommodityTemplateEnum.CommodityAttributeValue2.getCode());
        customerAttributeReactData2.setDataMap(customerAttributeMap);
        reactDataMap.add(customerAttributeReactData2);
        //属性3关联属性值3
        ExcelReactData customerAttributeReactData3 = new ExcelReactData();
        customerAttributeReactData3.setKeyIndex(CommodityTemplateEnum.CommodityAttribute3.getCode());
        customerAttributeReactData3.setValueIndex(CommodityTemplateEnum.CommodityAttributeValue3.getCode());
        customerAttributeReactData3.setDataMap(customerAttributeMap);
        reactDataMap.add(customerAttributeReactData3);
        //属性4关联属性值4
        ExcelReactData customerAttributeReactData4 = new ExcelReactData();
        customerAttributeReactData4.setKeyIndex(CommodityTemplateEnum.CommodityAttribute4.getCode());
        customerAttributeReactData4.setValueIndex(CommodityTemplateEnum.CommodityAttributeValue4.getCode());
        customerAttributeReactData4.setDataMap(customerAttributeMap);
        reactDataMap.add(customerAttributeReactData4);
        //属性5关联属性值5
        ExcelReactData customerAttributeReactData5 = new ExcelReactData();
        customerAttributeReactData5.setKeyIndex(CommodityTemplateEnum.CommodityAttribute5.getCode());
        customerAttributeReactData5.setValueIndex(CommodityTemplateEnum.CommodityAttributeValue5.getCode());
        customerAttributeReactData5.setDataMap(customerAttributeMap);
        reactDataMap.add(customerAttributeReactData5);

        //会员品类
        if(!CollectionUtils.isEmpty(customerCategoryNameList)){
            map.put(CommodityTemplateEnum.CustomerCategory.getCode(), customerCategoryNameList);
        }
        //商品品牌
        List<Brand> brandList = brandRepository.findByMemberIdAndMemberRoleIdAndStatusAndIsEnableOrderByApplyTimeDesc(sysUser.getMemberId(), sysUser.getMemberRoleId(), BrandStatusEnum.Pass.getCode(), true);
        List<String> brandNameList = brandList.stream().map(brand -> brand.getName() + Constants.UNDERLINE_STR + brand.getId()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(brandNameList)){
            map.put(CommodityTemplateEnum.Brand.getCode(), brandNameList);
        }
        //单位和副单位
        Map<String, String> unitMap = redisStringUtils.hGetAll(Constants.REDIS_KEY_UNIT, Constants.REDIS_PLATFORM_MANAGE_INDEX);
        List<String> unitNameList = new ArrayList<>();
        unitMap.forEach((key, value) -> {
            String[] split = value.split(Constants.TRANSFER_STR + Constants.SPLIT_STR);
            unitNameList.add(split[0] + Constants.UNDERLINE_STR + key);
        });
        if(!CollectionUtils.isEmpty(unitNameList)){
            map.put(CommodityTemplateEnum.Unit.getCode(), unitNameList);
            map.put(CommodityTemplateEnum.SubUnit.getCode(), unitNameList);
        }
        //定价类型
        List<String> priceTypeNameList = Arrays.stream(PriceTypeEnum.values()).map(priceTypeEnum -> priceTypeEnum.getName() + Constants.UNDERLINE_STR + priceTypeEnum.getCode()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(priceTypeNameList)){
            map.put(CommodityTemplateEnum.PriceType.getCode(), priceTypeNameList);
        }
        //图片设置方式
        List<String> imageTypeList = Arrays.stream(ImageTypeEnum.values()).map(imageTypeEnum -> imageTypeEnum.getName() + Constants.UNDERLINE_STR + imageTypeEnum.getCode()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(imageTypeList)){
            map.put(CommodityTemplateEnum.ImageType.getCode(), imageTypeList);
        }
        //物料名称
        List<Goods> goodsList = goodsRepository.findByMemberIdAndMemberRoleId(sysUser.getMemberId(), sysUser.getMemberRoleId());
        List<String> goodsNameList = goodsList.stream().map(goods -> goods.getName() + Constants.UNDERLINE_STR + goods.getId()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(goodsNameList)){
            map.put(CommodityTemplateEnum.Goods.getCode(), goodsNameList);
        }
        //配送方式
        List<String> deliveryTypeList = Arrays.stream(DeliveryTypeEnum.values()).map(deliveryTypeEnum -> deliveryTypeEnum.getName() + Constants.UNDERLINE_STR + deliveryTypeEnum.getCode()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(deliveryTypeList)){
            map.put(CommodityTemplateEnum.DeliveryType.getCode(), deliveryTypeList);
        }
        //运费方式
        List<String> carriageTypeList = Arrays.stream(CarriageTypeEnum.values()).map(carriageTypeEnum -> carriageTypeEnum.getName() + Constants.UNDERLINE_STR + carriageTypeEnum.getCode()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(carriageTypeList)){
            map.put(CommodityTemplateEnum.CarriageType.getCode(), carriageTypeList);
        }
        //运费模板
        LogisticsMemberIdAndRoleIdReq logisticsMemberIdAndRoleIdReq = new LogisticsMemberIdAndRoleIdReq();
        logisticsMemberIdAndRoleIdReq.setMemberId(sysUser.getMemberId());
        logisticsMemberIdAndRoleIdReq.setRoleId(sysUser.getMemberRoleId());
        logisticsMemberIdAndRoleIdReq.setCooperateType(CooperateTypeEnum.MERCHANT.getCode());
        Wrapper<List<FreightTemplateFeignRes>> TemplateFeignResWrapper = logisticsSelectControllerFeign.listFreightTemplate(logisticsMemberIdAndRoleIdReq);
        if(ResponseCode.SUCCESS.getCode() == TemplateFeignResWrapper.getCode()){
            List<FreightTemplateFeignRes> feignResList = TemplateFeignResWrapper.getData();
            if(!CollectionUtils.isEmpty(feignResList)){
                List<String> freightTemplateList = feignResList.stream().map(freightTemplateFeignRes -> freightTemplateFeignRes.getName() + Constants.UNDERLINE_STR + freightTemplateFeignRes.getId()).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(freightTemplateList)){
                    map.put(CommodityTemplateEnum.Template.getCode(), freightTemplateList);
                }
            }
        }else{
            throw new BusinessException(TemplateFeignResWrapper.getCode(), TemplateFeignResWrapper.getMessage());
        }
        //发货地址
        Wrapper<List<ShipperAddressSelectFeignRes>> sendAddressWrapper = logisticsSelectControllerFeign.listShipperAddress(logisticsMemberIdAndRoleIdReq);
        if(ResponseCode.SUCCESS.getCode() == sendAddressWrapper.getCode()){
            List<ShipperAddressSelectFeignRes> sendAddressDataList = sendAddressWrapper.getData();
            if(!CollectionUtils.isEmpty(sendAddressDataList)){
                List<String> sendAddressList = sendAddressDataList.stream().map(sendAddressData -> sendAddressData.getFullAddress() + Constants.UNDERLINE_STR + sendAddressData.getId()).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(sendAddressList)){
                    map.put(CommodityTemplateEnum.SendAddress.getCode(), sendAddressList);
                }
            }
        }else{
            throw new BusinessException(sendAddressWrapper.getCode(), sendAddressWrapper.getMessage());
        }
        //物流公司
        LogisticsSelectCompanyListFeignReq logisticsSelectCompanyListFeignReq = new LogisticsSelectCompanyListFeignReq();
        logisticsSelectCompanyListFeignReq.setMemberId(sysUser.getMemberId());
        logisticsSelectCompanyListFeignReq.setRoleId(sysUser.getMemberRoleId());
        logisticsSelectCompanyListFeignReq.setCooperateType(CooperateTypeEnum.MERCHANT.getCode());
        Wrapper<List<CommonSelectResponse>> companyListWrapper = logisticsSelectControllerFeign.listCompany(logisticsSelectCompanyListFeignReq);
        if(ResponseCode.SUCCESS.getCode() == companyListWrapper.getCode()){
            List<CommonSelectResponse> companyDataList = companyListWrapper.getData();
            if(!CollectionUtils.isEmpty(companyDataList)){
                List<String> companyList = companyDataList.stream().map(companyData -> companyData.getName() + Constants.UNDERLINE_STR + companyData.getId()).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(companyList)){
                    map.put(CommodityTemplateEnum.Company.getCode(), companyList);
                }
            }
        }else{
            throw new BusinessException(companyListWrapper.getCode(), companyListWrapper.getMessage());
        }

        //生成excel文档
        ExcelUtil.createExcelTemplate("commodityTemplate", headerList, map, reactDataMap, request, response);
    }

    /**
     * 导入商品
     * @param file  商品文件
     * @return 导入情况说明
     */
    @Override
    public Boolean importCommodity(UserLoginCacheDTO sysUser, MultipartFile file) {
        //临时变量
        Map<Long, CustomerCategory> customerCategoryMap = new HashMap<>();
        Map<Long, CustomerAttribute> customerAttributeMap = new HashMap<>();
        Map<Long, CustomerAttributeValue> customerAttributeValueMap = new HashMap<>();
        Map<Long, Brand> brandMap = new HashMap<>();
        Map<Long, Goods> goodsMap = new HashMap<>();
        Map<Long, String> unitMap = new HashMap<>();
        Map<String, String> imageMap = new HashMap<>();

        //获取excel表格中的数据
        List<CommodityImport> commodityImportList = analysisData(file);
        //校验excel表格中的数据
        Boolean flag = checkData(sysUser, commodityImportList, customerCategoryMap, customerAttributeMap, customerAttributeValueMap, brandMap, goodsMap, unitMap, imageMap);
        if(flag){
            //保存到数据库
            return saveCommodityImport(sysUser, commodityImportList, customerCategoryMap, customerAttributeMap, customerAttributeValueMap, brandMap, goodsMap, unitMap, imageMap);
        }
        return false;
    }

    /**
     * 解析excel文档
     */
    private List<CommodityImport> analysisData(MultipartFile file){
        List<CommodityImport> commodityImportList = new ArrayList<>();
        Workbook wb;
        try{
            //读取文件流
            InputStream iso = file.getInputStream();
            //判断是03版还是07版
            String originalFileName = file.getOriginalFilename();
            if (!StringUtils.isEmpty(originalFileName)) {
                if (ExcelUtil.isExcel2003(originalFileName)) {
                    wb = new HSSFWorkbook(iso);
                } else if (ExcelUtil.isExcel2007(originalFileName)) {
                    wb = new XSSFWorkbook(iso);
                } else {
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_IMPORT_TABLE_EXCEPTION);
                }
            } else {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_IMPORT_TABLE_EXCEPTION);
            }
        }catch (Exception e){
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_IMPORT_TABLE_ANALYSIS_EXCEPTION);
        }
        //只接收第一个sheet
        Sheet sheet = wb.getSheetAt(0);
        //一次最多只能导入1000行
        int lastRowNum = sheet.getLastRowNum();
        if(lastRowNum > 1001){
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_IMPORT_TABLE_SIZE_EXCEPTION);
        }
        //从第二行开始解析
        for (int i = 1; i <= lastRowNum; i++) {
            Row row = sheet.getRow(i);
            if (null == row) {
                continue;
            }
            //解析每一行数据
            String name = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Name.getCode() - 1));
            String slogan = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Slogan.getCode() - 1));
            String sellingPoint1 = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.SellingPoint1.getCode() - 1));
            String sellingPoint2 = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.SellingPoint2.getCode() - 1));
            String sellingPoint3 = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.SellingPoint3.getCode() - 1));
            String customerCategory = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.CustomerCategory.getCode() - 1));
            String brand = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Brand.getCode() - 1));
            String unit = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Unit.getCode() - 1));
            String subUnit = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.SubUnit.getCode() - 1));
            String minOrder = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.MinOrder.getCode() - 1));
            String priceType = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.PriceType.getCode() - 1));
            String imageType = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.ImageType.getCode() - 1));
            String image = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Image.getCode() - 1));
            String video = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Video.getCode() - 1));
            String word = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Word.getCode() - 1));
            String commodityAttribute1 = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.CommodityAttribute1.getCode() - 1));
            String commodityAttributeValue1 = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.CommodityAttributeValue1.getCode() - 1));
            String commodityAttribute2 = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.CommodityAttribute2.getCode() - 1));
            String commodityAttributeValue2 = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.CommodityAttributeValue2.getCode() - 1));
            String commodityAttribute3 = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.CommodityAttribute3.getCode() - 1));
            String commodityAttributeValue3 = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.CommodityAttributeValue3.getCode() - 1));
            String commodityAttribute4 = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.CommodityAttribute4.getCode() - 1));
            String commodityAttributeValue4 = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.CommodityAttributeValue4.getCode() - 1));
            String commodityAttribute5 = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.CommodityAttribute5.getCode() - 1));
            String commodityAttributeValue5 = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.CommodityAttributeValue5.getCode() - 1));
            String SKUImage = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.SKUImage.getCode() - 1));
            String price = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Price.getCode() - 1));
            String priceRate = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.PriceRate.getCode() - 1));
            String goods = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Goods.getCode() - 1));
            String deliveryType = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.DeliveryType.getCode() - 1));
            String carriageType = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.CarriageType.getCode() - 1));
            String weight = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Weight.getCode() - 1));
            String template = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Template.getCode() - 1));
            String sendAddress = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.SendAddress.getCode() - 1));
            String company = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Company.getCode() - 1));
            String sendCycle = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.SendCycle.getCode() - 1));
            String title = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Title.getCode() - 1));
            String description = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Description.getCode() - 1));
            String keywords = ExcelUtil.getCellValue(row.getCell(CommodityTemplateEnum.Keywords.getCode() - 1));
            //将每一行数据赋值给对象
            CommodityImport commodityImport = new CommodityImport();
            commodityImport.setIndex(i);
            commodityImport.setName(name);
            commodityImport.setSlogan(slogan);
            commodityImport.setSellingPoint1(sellingPoint1);
            commodityImport.setSellingPoint2(sellingPoint2);
            commodityImport.setSellingPoint3(sellingPoint3);
            commodityImport.setCustomerCategory(customerCategory);
            commodityImport.setBrand(brand);
            commodityImport.setUnit(unit);
            commodityImport.setSubUnit(subUnit);
            commodityImport.setMinOrder(minOrder);
            commodityImport.setPriceType(priceType);
            commodityImport.setGoods(goods);
            commodityImport.setImageType(imageType);
            commodityImport.setImage(image);
            commodityImport.setVideo(video);
            commodityImport.setWord(word);
            commodityImport.setCommodityAttribute1(commodityAttribute1);
            commodityImport.setCommodityAttributeValue1(commodityAttributeValue1);
            commodityImport.setCommodityAttribute2(commodityAttribute2);
            commodityImport.setCommodityAttributeValue2(commodityAttributeValue2);
            commodityImport.setCommodityAttribute3(commodityAttribute3);
            commodityImport.setCommodityAttributeValue3(commodityAttributeValue3);
            commodityImport.setCommodityAttribute4(commodityAttribute4);
            commodityImport.setCommodityAttributeValue4(commodityAttributeValue4);
            commodityImport.setCommodityAttribute5(commodityAttribute5);
            commodityImport.setCommodityAttributeValue5(commodityAttributeValue5);
            commodityImport.setSKUImage(SKUImage);
            commodityImport.setPrice(price);
            commodityImport.setPriceRate(priceRate);
            commodityImport.setDeliveryType(deliveryType);
            commodityImport.setCarriageType(carriageType);
            commodityImport.setWeight(weight);
            commodityImport.setTemplate(template);
            commodityImport.setSendAddress(sendAddress);
            commodityImport.setCompany(company);
            commodityImport.setSendCycle(sendCycle);
            commodityImport.setTitle(title);
            commodityImport.setDescription(description);
            commodityImport.setKeywords(keywords);
            //添加到集合中
            commodityImportList.add(commodityImport);
        }
        //如果表格没数据直接提示异常
        if(CollectionUtils.isEmpty(commodityImportList)){
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_IMPORT_TABLE_IS_NULL);
        }
        return commodityImportList;
    }

    /**
     * 校验excel表格的数据
     */
    private Boolean checkData(UserLoginCacheDTO sysUser, List<CommodityImport> commodityImportList, Map<Long, CustomerCategory> customerCategoryMap, Map<Long, CustomerAttribute> customerAttributeMap, Map<Long, CustomerAttributeValue> customerAttributeValueMap, Map<Long, Brand> brandMap, Map<Long, Goods> goodsMap, Map<Long, String> unitMap, Map<String, String> imageMap){
        //会员品类
        List<CustomerCategory> customerCategoryList = customerCategoryRepository.findByMemberIdAndMemberRoleId(sysUser.getMemberId(), sysUser.getMemberRoleId());
        List<Long> customerCategoryIdList = new ArrayList<>();
        customerCategoryList.forEach(customerCategory -> {
            customerCategoryIdList.add(customerCategory.getId());
            customerCategoryMap.put(customerCategory.getId(), customerCategory);
        });
        //会员属性
        List<Long> customerAttributeIdList = new ArrayList<>();
        List<Long> customerAttributeValueIdList = new ArrayList<>();
        customerCategoryList.forEach(customerCategory -> customerCategory.getCustomerAttributeList().stream().filter(customerAttribute -> customerAttribute.getIsSearch() && customerAttribute.getIsEnable()).forEach(customerAttribute -> {
            customerAttributeIdList.add(customerAttribute.getId());
            customerAttributeMap.put(customerAttribute.getId(), customerAttribute);
            List<CustomerAttributeValue> customerAttributeValueList = customerAttribute.getCustomerAttributeValueList();
            customerAttributeValueList.forEach(customerAttributeValue -> {
                customerAttributeValueIdList.add(customerAttributeValue.getId());
                customerAttributeValueMap.put(customerAttributeValue.getId(), customerAttributeValue);
            });
        }));
        //商品品牌
        List<Brand> brandList = brandRepository.findByMemberIdAndMemberRoleIdAndStatusAndIsEnableOrderByApplyTimeDesc(sysUser.getMemberId(), sysUser.getMemberRoleId(), BrandStatusEnum.Pass.getCode(), true);
        List<Long> brandIdList = new ArrayList<>();
        brandList.forEach(brand -> {
            brandIdList.add(brand.getId());
            brandMap.put(brand.getId(), brand);
        });
        //单位和副单位
        Map<String, String> unitRedisMap = redisStringUtils.hGetAll(Constants.REDIS_KEY_UNIT, Constants.REDIS_PLATFORM_MANAGE_INDEX);
        List<Long> unitIdList = new ArrayList<>();
        unitRedisMap.forEach((key, value) -> {
            unitIdList.add(Long.valueOf(key));
            unitMap.put(Long.valueOf(key), value);
        });
        //定价类型
        List<Long> priceTypeList = Arrays.stream(PriceTypeEnum.values()).map(priceTypeEnum -> Long.valueOf(priceTypeEnum.getCode())).collect(Collectors.toList());
        //图片设置方式
        List<Long> imageTypeList = Arrays.stream(ImageTypeEnum.values()).map(imageTypeEnum -> Long.valueOf(imageTypeEnum.getCode())).collect(Collectors.toList());
        //物料编号
        List<Goods> goodsList = goodsRepository.findByMemberIdAndMemberRoleId(sysUser.getMemberId(), sysUser.getMemberRoleId());
        List<Long> goodsIdList = new ArrayList<>();
        goodsList.forEach(goods -> {
            goodsIdList.add(goods.getId());
            goodsMap.put(goods.getId(), goods);
        });
        //配送方式
        List<Long> deliveryTypeList = Arrays.stream(DeliveryTypeEnum.values()).map(deliveryTypeEnum -> Long.valueOf(deliveryTypeEnum.getCode())).collect(Collectors.toList());
        //运费方式
        List<Long> carriageTypeList = Arrays.stream(CarriageTypeEnum.values()).map(carriageTypeEnum -> Long.valueOf(carriageTypeEnum.getCode())).collect(Collectors.toList());
        //运费模板
        List<Long> freightTemplateIdList = null;
        LogisticsMemberIdAndRoleIdReq logisticsMemberIdAndRoleIdReq = new LogisticsMemberIdAndRoleIdReq();
        logisticsMemberIdAndRoleIdReq.setMemberId(sysUser.getMemberId());
        logisticsMemberIdAndRoleIdReq.setRoleId(sysUser.getMemberRoleId());
        logisticsMemberIdAndRoleIdReq.setCooperateType(CooperateTypeEnum.MERCHANT.getCode());
        Wrapper<List<FreightTemplateFeignRes>> TemplateFeignResWrapper = logisticsSelectControllerFeign.listFreightTemplate(logisticsMemberIdAndRoleIdReq);
        if(ResponseCode.SUCCESS.getCode() == TemplateFeignResWrapper.getCode()){
            List<FreightTemplateFeignRes> feignResList = TemplateFeignResWrapper.getData();
            if(!CollectionUtils.isEmpty(feignResList)){
                freightTemplateIdList = feignResList.stream().map(FreightTemplateFeignRes::getId).collect(Collectors.toList());
            }
        }else{
            throw new BusinessException(TemplateFeignResWrapper.getCode(), TemplateFeignResWrapper.getMessage());
        }
        //发货地址
        List<Long> sendAddressIdList = null;
        Wrapper<List<ShipperAddressSelectFeignRes>> sendAddressWrapper = logisticsSelectControllerFeign.listShipperAddress(logisticsMemberIdAndRoleIdReq);
        if(ResponseCode.SUCCESS.getCode() == sendAddressWrapper.getCode()){
            List<ShipperAddressSelectFeignRes> sendAddressDataList = sendAddressWrapper.getData();
            if(!CollectionUtils.isEmpty(sendAddressDataList)){
                sendAddressIdList = sendAddressDataList.stream().map(ShipperAddressSelectFeignRes::getId).collect(Collectors.toList());
            }
        }else{
            throw new BusinessException(sendAddressWrapper.getCode(), sendAddressWrapper.getMessage());
        }
        //物流公司
        List<Long> companyIdList = null;
        LogisticsSelectCompanyListFeignReq logisticsSelectCompanyListFeignReq = new LogisticsSelectCompanyListFeignReq();
        logisticsSelectCompanyListFeignReq.setMemberId(sysUser.getMemberId());
        logisticsSelectCompanyListFeignReq.setRoleId(sysUser.getMemberRoleId());
        logisticsSelectCompanyListFeignReq.setCooperateType(CooperateTypeEnum.MERCHANT.getCode());
        Wrapper<List<CommonSelectResponse>> companyListWrapper = logisticsSelectControllerFeign.listCompany(logisticsSelectCompanyListFeignReq);
        if(ResponseCode.SUCCESS.getCode() == companyListWrapper.getCode()){
            List<CommonSelectResponse> companyDataList = companyListWrapper.getData();
            if(!CollectionUtils.isEmpty(companyDataList)){
                companyIdList = companyDataList.stream().map(CommonSelectResponse::getId).collect(Collectors.toList());
            }
        }else{
            throw new BusinessException(companyListWrapper.getCode(), companyListWrapper.getMessage());
        }
        //获取素材库的数据
        List<String> materialFileNameList = new ArrayList<>();
        MaterialFileInfoDTO materialFileInfoDTO = new MaterialFileInfoDTO();
        materialFileInfoDTO.setMemberId(sysUser.getMemberId());
        materialFileInfoDTO.setMemberRoleId(sysUser.getMemberRoleId());
        Wrapper<List<MaterialFileFeignVO>> materialFileWrapper = materialLibraryFeignController.findAllByMemberIdAndRoleId(materialFileInfoDTO);
        if(ResponseCode.SUCCESS.getCode() == materialFileWrapper.getCode()){
            List<MaterialFileFeignVO> materialFileDataList = materialFileWrapper.getData();
            if(!CollectionUtils.isEmpty(materialFileDataList)){
                materialFileDataList.forEach(materialFileData -> {
                    materialFileNameList.add(materialFileData.getFileName());
                    imageMap.put(materialFileData.getFileName(), materialFileData.getUrl());
                });
            }
        }else{
            throw new BusinessException(materialFileWrapper.getCode(), materialFileWrapper.getMessage());
        }

        //商品信息
        List<Commodity> commodityList = commodityRepository.findByMemberIdAndMemberRoleId(sysUser.getMemberId(), sysUser.getMemberRoleId());
        List<String> commodityNameList = commodityList.stream().map(Commodity::getName).collect(Collectors.toList());

        //用来判断同一个商品的单选属性是否重复
        Map<String, Map<String, String>> existCommodityAttributeMap = new HashMap<>();

        //遍历每一行的数据
        StringBuilder errorStr = new StringBuilder();
        for(CommodityImport commodityImport : commodityImportList){
            int i = commodityImport.getIndex();

            //检验商品名称
            if(!CollectionUtils.isEmpty(commodityNameList) && commodityNameList.contains(commodityImport.getName())){
                String error = "第" + (i + 1) + "行,商品名称: " + commodityImport.getName() + "已经存在,商品名称不能重复\r\n";
                errorStr.append(error);
            }

            //校验必填项
            checkIsEmpty(errorStr, i, commodityImport.getName(), CommodityTemplateEnum.Name.getName());
            checkIsEmpty(errorStr, i, commodityImport.getUnit(), CommodityTemplateEnum.Unit.getName());
            checkIsEmpty(errorStr, i, commodityImport.getPriceType(), CommodityTemplateEnum.PriceType.getName());
            checkIsEmpty(errorStr, i, commodityImport.getCustomerCategory(), CommodityTemplateEnum.CustomerCategory.getName());
            checkIsEmpty(errorStr, i, commodityImport.getImageType(), CommodityTemplateEnum.ImageType.getName());
            checkIsEmpty(errorStr, i, commodityImport.getSKUImage(), CommodityTemplateEnum.SKUImage.getName());
            checkIsEmpty(errorStr, i, commodityImport.getDeliveryType(), CommodityTemplateEnum.DeliveryType.getName());
            checkIsEmpty(errorStr, i, commodityImport.getCarriageType(), CommodityTemplateEnum.CarriageType.getName());

            //检验下拉框
            checkSelect(errorStr, i, commodityImport.getBrand(), CommodityTemplateEnum.Brand.getName(), brandIdList);
            checkSelect(errorStr, i, commodityImport.getUnit(), CommodityTemplateEnum.Unit.getName(), unitIdList);
            checkSelect(errorStr, i, commodityImport.getSubUnit(), CommodityTemplateEnum.SubUnit.getName(), unitIdList);
            checkSelect(errorStr, i, commodityImport.getPriceType(), CommodityTemplateEnum.PriceType.getName(), priceTypeList);
            checkSelect(errorStr, i, commodityImport.getImageType(), CommodityTemplateEnum.ImageType.getName(), imageTypeList);
            checkSelect(errorStr, i, commodityImport.getCustomerCategory(), CommodityTemplateEnum.CustomerCategory.getName(), customerCategoryIdList);
            checkSelect(errorStr, i, commodityImport.getCommodityAttribute1(), CommodityTemplateEnum.CommodityAttribute1.getName(), customerAttributeIdList);
            checkSelect(errorStr, i, commodityImport.getCommodityAttributeValue1(), CommodityTemplateEnum.CommodityAttributeValue1.getName(), customerAttributeValueIdList);
            checkSelect(errorStr, i, commodityImport.getCommodityAttribute2(), CommodityTemplateEnum.CommodityAttribute2.getName(), customerAttributeIdList);
            checkSelect(errorStr, i, commodityImport.getCommodityAttributeValue2(), CommodityTemplateEnum.CommodityAttributeValue2.getName(), customerAttributeValueIdList);
            checkSelect(errorStr, i, commodityImport.getCommodityAttribute3(), CommodityTemplateEnum.CommodityAttribute3.getName(), customerAttributeIdList);
            checkSelect(errorStr, i, commodityImport.getCommodityAttributeValue3(), CommodityTemplateEnum.CommodityAttributeValue3.getName(), customerAttributeValueIdList);
            checkSelect(errorStr, i, commodityImport.getCommodityAttribute4(), CommodityTemplateEnum.CommodityAttribute4.getName(), customerAttributeIdList);
            checkSelect(errorStr, i, commodityImport.getCommodityAttributeValue4(), CommodityTemplateEnum.CommodityAttributeValue4.getName(), customerAttributeValueIdList);
            checkSelect(errorStr, i, commodityImport.getCommodityAttribute5(), CommodityTemplateEnum.CommodityAttribute5.getName(), customerAttributeIdList);
            checkSelect(errorStr, i, commodityImport.getCommodityAttributeValue5(), CommodityTemplateEnum.CommodityAttributeValue5.getName(), customerAttributeValueIdList);
            checkSelect(errorStr, i, commodityImport.getGoods(), CommodityTemplateEnum.Goods.getName(), goodsIdList);
            checkSelect(errorStr, i, commodityImport.getDeliveryType(), CommodityTemplateEnum.DeliveryType.getName(), deliveryTypeList);
            checkSelect(errorStr, i, commodityImport.getCarriageType(), CommodityTemplateEnum.CarriageType.getName(), carriageTypeList);
            checkSelect(errorStr, i, commodityImport.getTemplate(), CommodityTemplateEnum.Template.getName(), freightTemplateIdList);
            checkSelect(errorStr, i, commodityImport.getSendAddress(), CommodityTemplateEnum.SendAddress.getName(), sendAddressIdList);
            checkSelect(errorStr, i, commodityImport.getCompany(), CommodityTemplateEnum.Company.getName(), companyIdList);

            //检查单选属性是否重复
            checkSimpleSelect(errorStr, i, commodityImport.getName(), CommodityTemplateEnum.CommodityAttribute1.getName(), commodityImport.getCommodityAttribute1(), commodityImport.getCommodityAttributeValue1(), customerAttributeMap, existCommodityAttributeMap);
            checkSimpleSelect(errorStr, i, commodityImport.getName(), CommodityTemplateEnum.CommodityAttribute2.getName(), commodityImport.getCommodityAttribute2(), commodityImport.getCommodityAttributeValue2(), customerAttributeMap, existCommodityAttributeMap);
            checkSimpleSelect(errorStr, i, commodityImport.getName(), CommodityTemplateEnum.CommodityAttribute3.getName(), commodityImport.getCommodityAttribute3(), commodityImport.getCommodityAttributeValue3(), customerAttributeMap, existCommodityAttributeMap);
            checkSimpleSelect(errorStr, i, commodityImport.getName(), CommodityTemplateEnum.CommodityAttribute4.getName(), commodityImport.getCommodityAttribute4(), commodityImport.getCommodityAttributeValue4(), customerAttributeMap, existCommodityAttributeMap);
            checkSimpleSelect(errorStr, i, commodityImport.getName(), CommodityTemplateEnum.CommodityAttribute5.getName(), commodityImport.getCommodityAttribute5(), commodityImport.getCommodityAttributeValue5(), customerAttributeMap, existCommodityAttributeMap);

            //检验是否数字类型
            checkDouble(errorStr, i, commodityImport.getMinOrder(), CommodityTemplateEnum.MinOrder.getName());
            checkDouble(errorStr, i, commodityImport.getWeight(), CommodityTemplateEnum.Weight.getName());
            checkDouble(errorStr, i, commodityImport.getPrice(), CommodityTemplateEnum.Price.getName());
            checkDouble(errorStr, i, commodityImport.getPriceRate(), CommodityTemplateEnum.PriceRate.getName());
            checkInt(errorStr, i, commodityImport.getSendCycle(), CommodityTemplateEnum.SendCycle.getName());

            //校验长度
            checkLength(errorStr, i, commodityImport.getName(), CommodityTemplateEnum.Name.getName(), 90);
            checkLength(errorStr, i, commodityImport.getSlogan(), CommodityTemplateEnum.Slogan.getName(), 90);
            checkLength(errorStr, i, commodityImport.getSellingPoint1(), CommodityTemplateEnum.SellingPoint1.getName(), 50);
            checkLength(errorStr, i, commodityImport.getSellingPoint2(), CommodityTemplateEnum.SellingPoint2.getName(), 50);
            checkLength(errorStr, i, commodityImport.getSellingPoint3(), CommodityTemplateEnum.SellingPoint3.getName(), 50);
            checkLength(errorStr, i, commodityImport.getUnit(), CommodityTemplateEnum.Unit.getName(), 20);
            checkLength(errorStr, i, commodityImport.getSubUnit(), CommodityTemplateEnum.SubUnit.getName(), 20);

            //校验图片和视频是否存在素材库
            checkFile(errorStr, i, commodityImport.getImage(), CommodityTemplateEnum.Image.getName(), materialFileNameList);
            checkFile(errorStr, i, commodityImport.getVideo(), CommodityTemplateEnum.Video.getName(), materialFileNameList);
            checkFile(errorStr, i, commodityImport.getSKUImage(), CommodityTemplateEnum.SKUImage.getName(), materialFileNameList);

            //校验属性1-5是否重复
            int count = 0;
            Set<String> attributeSet = new HashSet<>();
            String commodityAttribute1 = commodityImport.getCommodityAttribute1();
            if(StringUtils.isNotEmpty(commodityAttribute1)){
                attributeSet.add(commodityAttribute1);
                count ++;
            }
            String commodityAttribute2 = commodityImport.getCommodityAttribute2();
            if(StringUtils.isNotEmpty(commodityAttribute2)){
                attributeSet.add(commodityAttribute2);
                count ++;
            }
            String commodityAttribute3 = commodityImport.getCommodityAttribute3();
            if(StringUtils.isNotEmpty(commodityAttribute3)){
                attributeSet.add(commodityAttribute3);
                count ++;
            }
            String commodityAttribute4 = commodityImport.getCommodityAttribute4();
            if(StringUtils.isNotEmpty(commodityAttribute4)){
                attributeSet.add(commodityAttribute4);
                count ++;
            }
            String commodityAttribute5 = commodityImport.getCommodityAttribute5();
            if(StringUtils.isNotEmpty(commodityAttribute5)){
                attributeSet.add(commodityAttribute5);
                count ++;
            }
            if(attributeSet.size() != count){
                String error = "第" + (i + 1) + "行,属性1-5出现重复组合\r\n";
                errorStr.append(error);
            }
        }
        //如果出现错误信息，代表校验不通过
        if(errorStr.length() > 0){
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_IMPORT_TABLE_DATA_EXCEPTION, errorStr.toString());
        }
        return true;
    }

    /**
     * 校验单选属性是否重复
     */
    private void checkSimpleSelect(StringBuilder errorStr, int index, String commodityName, String columnName, String commodityAttribute, String commodityAttributeValue, Map<Long, CustomerAttribute> customerAttributeMap, Map<String, Map<String, String>> existCommodityAttributeMap){
        if(StringUtils.isNotEmpty(commodityAttribute) && StringUtils.isNotEmpty(commodityAttributeValue)){
            //获取属性
            Long commodityAttributeId = Long.parseLong(commodityAttribute.substring(commodityAttribute.lastIndexOf(Constants.UNDERLINE_STR) + 1));
            CustomerAttribute customerAttribute = customerAttributeMap.get(commodityAttributeId);
            //判断属性是否为单选属性
            if(customerAttribute != null && customerAttribute.getType() == 1){
                //获取该商品对应的属性和属性值
                Map<String, String> existCommodityAttributeValueMap = existCommodityAttributeMap.get(commodityName);
                if(existCommodityAttributeValueMap != null){
                    //获取该商品的属性在map中已经存在的属性值
                    String existCommodityAttributeValue = existCommodityAttributeValueMap.get(commodityAttribute);
                    //判断该商品的属性是否已经存在属性值
                    if(StringUtils.isNotEmpty(existCommodityAttributeValue)){
                        //该商品的属性已经存在属性值，则判断当前新加的属性值是否一样
                        if(!existCommodityAttributeValue.equals(commodityAttributeValue)){
                            String error = "第" + (index + 1) + "行," + columnName + ": " + commodityAttribute + "为单选，同一个商品不能同时出现多个属性值\r\n";
                            errorStr.append(error);
                        }
                    }else{
                        //该商品的属性不存在属性值，则添加第一个属性值
                        existCommodityAttributeValueMap.put(commodityAttribute, commodityAttributeValue);
                        existCommodityAttributeMap.put(commodityName, existCommodityAttributeValueMap);
                    }
                }else{
                    //该商品对应的属性和属性值第一次出现就存入map中
                    existCommodityAttributeValueMap = new HashMap<>();
                    existCommodityAttributeValueMap.put(commodityAttribute, commodityAttributeValue);
                    existCommodityAttributeMap.put(commodityName, existCommodityAttributeValueMap);
                }
            }
        }
    }

    /**
     * 校验必填项
     */
    private void checkIsEmpty(StringBuilder errorStr, int index, String value, String columnName){
        if (StringUtils.isEmpty(value)) {
            String error = "第" + (index + 1) + "行," + columnName + "\r\n";
            errorStr.append(error);
        }
    }

    /**
     * 校验下拉框
     */
    private void checkSelect(StringBuilder errorStr, int index, String value, String columnName, List<Long> idList){
        if(StringUtils.isNotEmpty(value)){
            if (!CollectionUtils.isEmpty(idList) && value.contains(Constants.UNDERLINE_STR)) {
                Long id = Long.parseLong(value.substring(value.lastIndexOf(Constants.UNDERLINE_STR) + 1));
                if(!idList.contains(id)){
                    String error = "第" + (index + 1) + "行," + columnName + ":" + value + ",不存在\r\n";
                    errorStr.append(error);
                }
            }else{
                String error = "第" + (index + 1) + "行," + columnName + ":" + value + ",不存在\r\n";
                errorStr.append(error);
            }
        }
    }

    /**
     * 检验是否为Double类型
     */
    private void checkDouble(StringBuilder errorStr, int index, String value, String columnName){
        try{
            if(StringUtils.isNotEmpty(value)){
                double v = Double.parseDouble(value);
                if(v < 0 || v > Double.MAX_VALUE){
                    String error = "第" + (index + 1) + "行," + columnName + ":" + value + ",数字不合法\r\n";
                    errorStr.append(error);
                }
            }
        }catch (Exception e){
            String error = "第" + (index + 1) + "行," + columnName + ":" + value + ",必须为数字类型\r\n";
            errorStr.append(error);
        }
    }

    /**
     * 检验是否为Int类型
     */
    private void checkInt(StringBuilder errorStr, int index, String value, String columnName){
        try{
            if(StringUtils.isNotEmpty(value)){
                int v = Integer.parseInt(value);
                if(v < 0 || v >= Integer.MAX_VALUE){
                    String error = "第" + (index + 1) + "行," + columnName + ":" + value + ",数字不合法\r\n";
                    errorStr.append(error);
                }
            }
        }catch (Exception e){
            String error = "第" + (index + 1) + "行," + columnName + ":" + value + ",必须为数字类型\r\n";
            errorStr.append(error);
        }
    }

    /**
     * 检验输入字段长度
     */
    private void checkLength(StringBuilder errorStr, int index, String value, String columnName, int len){
        if(StringUtils.isNotEmpty(value)){
            if(stringLength(value) > len){
                String error = "第" + (index + 1) + "行," + columnName + ":" + value + ",长度大于" + len + "个字符\r\n";
                errorStr.append(error);
            }
        }
    }

    /**
     * 获取长度(汉字代表2个字符)
     */
    private int stringLength(String value) {
        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 2;
            } else {
                valueLength += 1;
            }
        }
        return valueLength;
    }

    /**
     * 校验图片和视频是否存在素材库
     */
    private void checkFile(StringBuilder errorStr, int index, String value, String columnName, List<String> fileNameList){
        if(StringUtils.isNotEmpty(value)){
            if (!CollectionUtils.isEmpty(fileNameList)) {
                String[] split = value.split(Constants.COMMA_STR);
                for(String file : split){
                    if(!fileNameList.contains(file)){
                        String error = "第" + (index + 1) + "行," + columnName + ":" + value + ",没有在素材库中匹配到\r\n";
                        errorStr.append(error);
                    }
                }
            }else{
                String error = "第" + (index + 1) + "行," + columnName + ":" + value + ",没有在素材库中匹配到\r\n";
                errorStr.append(error);
            }
        }
    }

    /**
     * 保存excel导入的商品
     */
    private Boolean saveCommodityImport(UserLoginCacheDTO sysUser, List<CommodityImport> commodityImportList, Map<Long, CustomerCategory> customerCategoryMap, Map<Long, CustomerAttribute> customerAttributeMap, Map<Long, CustomerAttributeValue> customerAttributeValueMap, Map<Long, Brand> brandMap, Map<Long, Goods> goodsMap, Map<Long, String> unitMap, Map<String, String> imageMap){
        String importBath = DateUtil.format(new Date(),"yyyyMMddHHmmss");
        //用于记录是否同一个商品(表格中多个sku只对应同一个商品名称)
        Map<String, Commodity> commodityMap = new HashMap<>();
        for(int i = 0; i < commodityImportList.size(); i ++){
            CommodityImport commodityImport = commodityImportList.get(i);

            //商品价格
            Double commodityPrice = 0D;
            String price = commodityImport.getPrice();
            if(StringUtils.isNotEmpty(price)){
                commodityPrice = Double.parseDouble(price);
            }
            //sku图片
            String skuImage = commodityImport.getSKUImage();
            //物料编号
            Goods goods = null;
            String goodsStr = commodityImport.getGoods();
            if(StringUtils.isNotEmpty(goodsStr)){
                goods = goodsMap.get(Long.valueOf(goodsStr.substring(goodsStr.lastIndexOf(Constants.UNDERLINE_STR) + 1)));
            }

            //判断是否出现同一个商品多条sku
            String commodityName = commodityImport.getName();
            Commodity commodity = commodityMap.get(commodityName);
            if(commodity != null){
                //已经存在的商品只增加商品属性组合和sku组合
                setCommodityAttributeAndSku(i, commodity, commodityPrice, skuImage,  commodity.getUnitPriceAndPicList(),  commodity.getCommodityAttributeList(), commodityImport, customerAttributeMap, customerAttributeValueMap, imageMap, goods);
            }else{
                //新建商品
                commodity = new Commodity();

                //会员品类
                Long customerCategoryId = Long.valueOf(commodityImport.getCustomerCategory().substring(commodityImport.getCustomerCategory().lastIndexOf(Constants.UNDERLINE_STR) + 1));
                commodity.setCustomerCategory(customerCategoryMap.get(customerCategoryId));

                //商品属性组合和sku组合
                setCommodityAttributeAndSku(i, commodity, commodityPrice, skuImage, new ArrayList<>(), new ArrayList<>(), commodityImport, customerAttributeMap, customerAttributeValueMap, imageMap, goods);

                //图片设置方式
                Integer imageType = Integer.parseInt(commodityImport.getImageType().substring(commodityImport.getImageType().lastIndexOf(Constants.UNDERLINE_STR) + 1));
                commodity.setIsAllAttributePic(ImageTypeEnum.All.getCode().equals(imageType));

                //品牌
                String brand = commodityImport.getBrand();
                if (StringUtils.isNotEmpty(brand)) {
                    commodity.setBrand(brandMap.get(Long.valueOf(brand.substring(brand.lastIndexOf(Constants.UNDERLINE_STR) + 1))));
                }
                //单位
                Long unitId = Long.valueOf(commodityImport.getUnit().substring(commodityImport.getUnit().lastIndexOf(Constants.UNDERLINE_STR) + 1));
                commodity.setUnitId(unitId);
                commodity.setUnitName(unitMap.get(unitId).split(Constants.TRANSFER_STR + Constants.SPLIT_STR)[0]);
                //副单位
                String subUnit = commodityImport.getSubUnit();
                if (StringUtils.isNotEmpty(subUnit)) {
                    Long subUnitId = Long.valueOf(subUnit.substring(subUnit.lastIndexOf(Constants.UNDERLINE_STR) + 1));
                    commodity.setSubUnitId(subUnitId);
                    commodity.setSubUnitName(unitMap.get(subUnitId).split(Constants.TRANSFER_STR + Constants.SPLIT_STR)[0]);
                }
                //产品定价类型
                Integer priceType = Integer.parseInt(commodityImport.getPriceType().substring(commodityImport.getPriceType().lastIndexOf(Constants.UNDERLINE_STR) + 1));
                commodity.setPriceType(priceType);
                //商品描述
                CommodityRemark commodityRemark = new CommodityRemark();
                //商品描述-图片
                String image = commodityImport.getImage();
                if(StringUtils.isNotEmpty(image)){
                    List<CommodityRemarkImage> commodityRemarkImageList = new ArrayList<>();
                    String[] split = image.split(Constants.COMMA_STR);
                    for(String fileName : split){
                        CommodityRemarkImage commodityRemarkImage = new CommodityRemarkImage();
                        commodityRemarkImage.setCommodityRemark(commodityRemark);
                        commodityRemarkImage.setUrl(imageMap.get(fileName));
                        commodityRemarkImageList.add(commodityRemarkImage);
                    }
                    if(!CollectionUtils.isEmpty(commodityRemarkImageList)){
                        commodityRemark.setImageList(commodityRemarkImageList);
                    }
                }
                //商品描述-视频
                String video = commodityImport.getVideo();
                if(StringUtils.isNotEmpty(video)){
                    String[] split = video.split(Constants.COMMA_STR);
                    String[] videoArray = new String[split.length];
                    for(int j = 0; j < split.length; j ++){
                        videoArray[j] = imageMap.get(split[j]);
                    }
                    commodityRemark.setVideo(videoArray);
                }
                //商品描述-文字
                String word = commodityImport.getWord();
                if(StringUtils.isNotEmpty(word)){
                    String[] split = new String[]{word};
                    commodityRemark.setWord(split);
                }
                commodity.setCommodityRemark(commodityRemark);

                //物流信息
                LogisticsRequest logisticsRequest = new LogisticsRequest();
                String weight = commodityImport.getWeight();
                if(StringUtils.isNotEmpty(weight)){
                    logisticsRequest.setWeight(Double.valueOf(weight));
                }
                //物流信息-配送方式
                Integer deliveryType = Integer.parseInt(commodityImport.getDeliveryType().substring(commodityImport.getDeliveryType().lastIndexOf(Constants.UNDERLINE_STR) + 1));
                logisticsRequest.setDeliveryType(deliveryType);
                //物流信息-运费方式
                Integer carriageType = Integer.parseInt(commodityImport.getCarriageType().substring(commodityImport.getCarriageType().lastIndexOf(Constants.UNDERLINE_STR) + 1));
                logisticsRequest.setCarriageType(carriageType);
                //物流信息-物流公司
                String company = commodityImport.getCompany();
                if(StringUtils.isNotEmpty(company)){
                    logisticsRequest.setCompany(Long.valueOf(company.substring(company.lastIndexOf(Constants.UNDERLINE_STR) + 1)));
                }
                //物流信息-物流模板
                String template = commodityImport.getTemplate();
                if(StringUtils.isNotEmpty(template)){
                    logisticsRequest.setUseTemplate(true);
                    logisticsRequest.setTemplateId(Long.valueOf(template.substring(template.lastIndexOf(Constants.UNDERLINE_STR) + 1)));
                }
                //物流信息-发货地址
                String sendAddress = commodityImport.getSendAddress();
                if(StringUtils.isNotEmpty(sendAddress)){
                    logisticsRequest.setSendAddress(Long.valueOf(sendAddress.substring(sendAddress.lastIndexOf(Constants.UNDERLINE_STR) + 1)));
                }
                commodity.setLogistics(logisticsRequest);

                //最小价格和最大价格
                Double min = commodity.getMin();
                if(min != null){
                    if(min > commodityPrice){
                        commodity.setMin(commodityPrice);
                    }
                }else{
                    commodity.setMin(commodityPrice);
                }
                Double max = commodity.getMax();
                if(max != null){
                    if(max < commodityPrice){
                        commodity.setMax(commodityPrice);
                    }
                }else{
                    commodity.setMax(commodityPrice);
                }

                //最小起订
                String minOrder = commodityImport.getMinOrder();
                if(StringUtils.isNotEmpty(minOrder)){
                    commodity.setMinOrder(Double.valueOf(commodityImport.getMinOrder()));
                }
                //送货周期
                String sendCycle = commodityImport.getSendCycle();
                if(StringUtils.isNotEmpty(sendCycle)){
                    commodity.setSendCycle(Integer.parseInt(commodityImport.getSendCycle()));
                }
                //商品其他字段
                commodity.setStatus(CommodityStatusEnum.Not_Submitted.getCode());
                commodity.setName(commodityName);
                commodity.setSlogan(commodityImport.getSlogan());
                commodity.setSellingPoint(new String[]{commodityImport.getSellingPoint1(), commodityImport.getSellingPoint2(), commodityImport.getSellingPoint3()});
                commodity.setMemberId(sysUser.getMemberId());
                commodity.setMemberName(sysUser.getCompany());
                commodity.setMemberRoleId(sysUser.getMemberRoleId());
                commodity.setMemberRoleName(sysUser.getMemberRoleName());
                commodity.setUserId(sysUser.getUserId());
                commodity.setUserName(sysUser.getUserName());
                commodity.setTitle(commodityImport.getTitle());
                commodity.setDescription(commodityImport.getDescription());
                commodity.setKeywords(commodityImport.getKeywords());
                commodity.setImportBatch(importBath);
            }
            //将map中的商品替换成最新的
            commodityMap.put(commodityName, commodity);
        }

        //保存到数据库
        List<Commodity> commodityList = new ArrayList<>(commodityMap.values());
        commodityRepository.saveAll(commodityList);

        //添加商品编码(根据id转成6位32进制字符)
        commodityList.forEach(commodity -> commodity.setCode(Constants.COMMODITY_CODE_PREFIX + CodeUtils.digits32(commodity.getId(), Constants.CODE_NUM)));
        commodityRepository.saveAll(commodityList);

        //首页数据统计
        try {
            List<OperateNoticeVO> operateNoticeVOList = new ArrayList<>();
            //商品总数
            OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
            operateNoticeVO.setMemberId(sysUser.getMemberId());
            operateNoticeVO.setRoleId(sysUser.getMemberRoleId());
            operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
            operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.PRODUCT_COUNT.getCode());
            operateNoticeVO.setIncreaseCount((long) commodityList.size());
            operateNoticeVOList.add(operateNoticeVO);
            //待提交审核商品
            operateNoticeVO = new OperateNoticeVO();
            operateNoticeVO.setMemberId(sysUser.getMemberId());
            operateNoticeVO.setRoleId(sysUser.getMemberRoleId());
            operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
            operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_VALIFY_COMMIT.getCode());
            operateNoticeVO.setIncreaseCount((long) commodityList.size());
            operateNoticeVOList.add(operateNoticeVO);
            reportControllerFeign.addOperateNoticeList(operateNoticeVOList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 设置同一个商品的多个属性组合和sku组合
     */
    private void setCommodityAttributeAndSku(Integer index, Commodity commodity, Double commodityPrice, String skuImage, List<CommodityUnitPriceAndPic> unitPriceAndPicList, List<CommodityAttribute> commodityAttributeList, CommodityImport commodityImport, Map<Long, CustomerAttribute> customerAttributeMap, Map<Long, CustomerAttributeValue> customerAttributeValueMap, Map<String, String> imageMap, Goods goods){
        //sku图片(第一张为商品主图)
        if(StringUtils.isNotEmpty(skuImage) && StringUtils.isEmpty(commodity.getMainPic())){
            String[] split = skuImage.split(Constants.COMMA_STR);
            commodity.setMainPic(imageMap.get(split[0]));
        }
        //用于标识是同一个sku(属性1-5放在同一个sku中)
        Map<Integer, CommodityUnitPriceAndPic> commodityUnitPriceAndPicMap = new HashMap<>();
        //属性1和属性值1
        String commodityAttribute1 = commodityImport.getCommodityAttribute1();
        String commodityAttributeValue1 = commodityImport.getCommodityAttributeValue1();
        setAttributeAndSku(index, commodity, commodityPrice, skuImage,  unitPriceAndPicList,  commodityAttributeList, commodityAttribute1, commodityAttributeValue1, customerAttributeMap, customerAttributeValueMap, commodityUnitPriceAndPicMap, imageMap, goods);
        //属性2和属性值2
        String commodityAttribute2 = commodityImport.getCommodityAttribute2();
        String commodityAttributeValue2 = commodityImport.getCommodityAttributeValue2();
        setAttributeAndSku(index, commodity, commodityPrice, skuImage,  unitPriceAndPicList,  commodityAttributeList, commodityAttribute2, commodityAttributeValue2, customerAttributeMap, customerAttributeValueMap, commodityUnitPriceAndPicMap, imageMap, goods);
        //属性3和属性值3
        String commodityAttribute3 = commodityImport.getCommodityAttribute3();
        String commodityAttributeValue3 = commodityImport.getCommodityAttributeValue3();
        setAttributeAndSku(index, commodity, commodityPrice, skuImage,  unitPriceAndPicList,  commodityAttributeList, commodityAttribute3, commodityAttributeValue3, customerAttributeMap, customerAttributeValueMap, commodityUnitPriceAndPicMap, imageMap, goods);
        //属性4和属性值4
        String commodityAttribute4 = commodityImport.getCommodityAttribute4();
        String commodityAttributeValue4 = commodityImport.getCommodityAttributeValue4();
        setAttributeAndSku(index, commodity, commodityPrice, skuImage,  unitPriceAndPicList,  commodityAttributeList, commodityAttribute4, commodityAttributeValue4, customerAttributeMap, customerAttributeValueMap, commodityUnitPriceAndPicMap, imageMap, goods);
        //属性5和属性值5
        String commodityAttribute5 = commodityImport.getCommodityAttribute5();
        String commodityAttributeValue5 = commodityImport.getCommodityAttributeValue5();
        setAttributeAndSku(index, commodity, commodityPrice, skuImage,  unitPriceAndPicList,  commodityAttributeList, commodityAttribute5, commodityAttributeValue5, customerAttributeMap, customerAttributeValueMap, commodityUnitPriceAndPicMap, imageMap, goods);

        //商品属性
        if (!CollectionUtils.isEmpty(commodityAttributeList)) {
            commodity.setCommodityAttributeList(commodityAttributeList);
        }
        //商品sku
        if (!CollectionUtils.isEmpty(unitPriceAndPicList)) {
            commodity.setUnitPriceAndPicList(unitPriceAndPicList);
        }
    }

    /**
     * 设置同一个商品的同一个属性组合和sku组合
     */
    private void setAttributeAndSku(Integer index, Commodity commodity, Double commodityPrice, String skuImage, List<CommodityUnitPriceAndPic> unitPriceAndPicList, List<CommodityAttribute> commodityAttributeList, String commodityAttributeImport, String commodityAttributeValueImport, Map<Long, CustomerAttribute> customerAttributeMap, Map<Long, CustomerAttributeValue> customerAttributeValueMap, Map<Integer, CommodityUnitPriceAndPic> commodityUnitPriceAndPicMap, Map<String, String> imageMap, Goods goods){
        Map<CustomerAttribute, CommodityAttribute> commodityAttributeMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(commodityAttributeList)){
            commodityAttributeList.forEach(commodityAttribute -> commodityAttributeMap.put(commodityAttribute.getCustomerAttribute(), commodityAttribute));
        }
        if (StringUtils.isNotEmpty(commodityAttributeImport)) {
            Long commodityAttributeId = Long.valueOf(commodityAttributeImport.substring(commodityAttributeImport.lastIndexOf(Constants.UNDERLINE_STR) + 1));
            Long commodityAttributeValueId = 0L;
            CustomerAttribute customerAttribute = customerAttributeMap.get(commodityAttributeId);
            if (customerAttribute != null) {
                //如果出现相同的属性，只累加属性值
                CommodityAttribute commodityAttribute = commodityAttributeMap.get(customerAttribute);
                if(commodityAttribute == null){
                    //商品属性-属性1
                    commodityAttribute = new CommodityAttribute();
                    commodityAttribute.setCommodity(commodity);
                    commodityAttribute.setCustomerAttribute(customerAttribute);
                }
                if(StringUtils.isNotEmpty(commodityAttributeValueImport)){
                    commodityAttributeValueId = Long.valueOf(commodityAttributeValueImport.substring(commodityAttributeValueImport.lastIndexOf(Constants.UNDERLINE_STR) + 1));
                    CustomerAttributeValue customerAttributeValue = customerAttributeValueMap.get(commodityAttributeValueId);

                    //商品属性-属性值1(相同属性值添加到同一个属性中)
                    List<CustomerAttributeValue> customerAttributeValueList = commodityAttribute.getCustomerAttributeValueList();
                    if(CollectionUtils.isEmpty(customerAttributeValueList)){
                        customerAttributeValueList = new ArrayList<>();
                    }

                    //判断是否重复
                    if(!customerAttributeValueList.contains(customerAttributeValue)){
                        customerAttributeValueList.add(customerAttributeValue);
                        commodityAttribute.setCustomerAttributeValueList(customerAttributeValueList);
                    }
                }
                commodityAttributeList.add(commodityAttribute);

                //如果出现相同的sku，只累加sku中的属性组合
                CommodityUnitPriceAndPic commodityUnitPriceAndPic = commodityUnitPriceAndPicMap.get(index);
                if(commodityUnitPriceAndPic != null){
                    List<CommodityGoodsAttribute> attributeAndValueList = commodityUnitPriceAndPic.getAttributeAndValueList();
                    if(CollectionUtils.isEmpty(attributeAndValueList)){
                        attributeAndValueList = new ArrayList<>();
                    }
                    //商品sku-商品属性
                    CommodityGoodsAttribute commodityGoodsAttribute = new CommodityGoodsAttribute();
                    commodityGoodsAttribute.setCommodityUnitPriceAndPic(commodityUnitPriceAndPic);
                    commodityGoodsAttribute.setCustomerAttribute(customerAttribute);
                    if(StringUtils.isNotEmpty(commodityAttributeValueImport)){
                        CustomerAttributeValue customerAttributeValue = customerAttributeValueMap.get(commodityAttributeValueId);
                        //商品sku-属性值
                        commodityGoodsAttribute.setCustomerAttributeValue(customerAttributeValue);
                    }
                    attributeAndValueList.add(commodityGoodsAttribute);
                    commodityUnitPriceAndPic.setAttributeAndValueList(attributeAndValueList);
                }else{
                    //商品sku
                    commodityUnitPriceAndPic = new CommodityUnitPriceAndPic();
                    commodityUnitPriceAndPic.setCommodity(commodity);
                    commodityUnitPriceAndPic.setGoods(goods);
                    //商品sku-商品属性
                    List<CommodityGoodsAttribute> attributeAndValueList = new ArrayList<>();
                    CommodityGoodsAttribute commodityGoodsAttribute = new CommodityGoodsAttribute();
                    commodityGoodsAttribute.setCommodityUnitPriceAndPic(commodityUnitPriceAndPic);
                    commodityGoodsAttribute.setCustomerAttribute(customerAttribute);

                    if(StringUtils.isNotEmpty(commodityAttributeValueImport)){
                        CustomerAttributeValue customerAttributeValue = customerAttributeValueMap.get(commodityAttributeValueId);
                        //商品sku-属性值
                        commodityGoodsAttribute.setCustomerAttributeValue(customerAttributeValue);
                    }
                    attributeAndValueList.add(commodityGoodsAttribute);
                    commodityUnitPriceAndPic.setAttributeAndValueList(attributeAndValueList);

                    //商品sku-价格
                    commodityUnitPriceAndPic.setIsMorePrice(false);
                    Map<String,Double> unitPrice = new HashMap<>();
                    unitPrice.put("0-0", commodityPrice);
                    commodityUnitPriceAndPic.setUnitPrice(unitPrice);

                    //商品sku-图片
                    if(StringUtils.isNotEmpty(skuImage)){
                        String[] split = skuImage.split(Constants.COMMA_STR);
                        String[] skuImageArray = new String[split.length];
                        for(int i = 0; i < split.length; i ++){
                            skuImageArray[i] = imageMap.get(split[i]);
                        }
                        commodityUnitPriceAndPic.setCommodityPic(skuImageArray);
                    }

                    unitPriceAndPicList.add(commodityUnitPriceAndPic);
                }
                commodityUnitPriceAndPicMap.put(index, commodityUnitPriceAndPic);
            }
        }
    }

    /**
     * redis数据格式中获取品类名称
     * @param categoryId                    品类id
     * @param customerCategoryRedisMap      redis数据
     * @return 品类名称
     */
    private String getCustomerCategoryName(int categoryId, Map<String, String> customerCategoryRedisMap){
        String customerCategoryJson = customerCategoryRedisMap.get(String.valueOf(categoryId));
        if(StringUtils.isNotEmpty(customerCategoryJson)){
            CustomerCategory newCustomerCategory = JSONUtil.toBean(customerCategoryJson, CustomerCategory.class);
            return newCustomerCategory.getName();
        }else{
            return "";
        }
    }

    /**
     * 查询商品历史价格
     *
     * @param commoditySkuId 商品Skuid
     * @param days           最近多少天
     * @return 商品历史价格
     */
    @Override
    public CommodityPriceRecordResponse getPriceRecord(Long commoditySkuId, Integer days) {
        //定义返回对象
        CommodityPriceRecordResponse commodityPriceResponse = new CommodityPriceRecordResponse();
        //构建查询时间
        LocalDate startDate = DateUtil.toLocalDateTime(DateUtil.offsetDay(new Date(), days * -1)).toLocalDate();
        LocalDate endDate = DateUtil.toLocalDateTime(new Date()).toLocalDate();
        //查询商品价格记录
        List<CommodityPriceRecord> commodityPriceRecordList = priceRecordRepository.findByCommoditySkuIdAndDateBetweenOrderByDateAsc(commoditySkuId, startDate, endDate);
        if (commodityPriceRecordList != null && commodityPriceRecordList.size() > 0) {
            List<CommodityPriceRecordDetailResponse> commodityPriceRecordDetailList = commodityPriceRecordList.stream().map(commodityPriceRecord -> {
                CommodityPriceRecordDetailResponse commodityPriceRecordDetailResponse = BeanUtil.copyProperties(commodityPriceRecord, CommodityPriceRecordDetailResponse.class);
                commodityPriceRecordDetailResponse.setDateTimeStamp(commodityPriceRecord.getDate().atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli());
                return commodityPriceRecordDetailResponse;
            }).collect(Collectors.toList());
            commodityPriceResponse.setCommodityPriceRecordList(commodityPriceRecordDetailList);
        }
        //查询历史最低价格
        Double minPrice = priceRecordRepository.findMinPriceByCommoditySkuId(commoditySkuId);
        if (minPrice != null) {
            commodityPriceResponse.setMinPrice(minPrice);
        }
        return commodityPriceResponse;
    }

    /**
     * 查询常购清单列表
     *
     * @param pageVO  分页实体
     * @param shopId  商城id
     * @param sysUser 当前登录用户
     * @return 常购清单列表
     */
    @Override
    public PageData<OftenBuyCommodityResponse> getOftenBuyCommodityList(PageVO pageVO, Long shopId, String name, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Page<OftenBuyCommodity> result = oftenBuyCommodityRepository.findAll(getOftenBuyCommodityListSpecification(shopId, name, sysUser), page);
        List<OftenBuyCommodityResponse> oftenBuyCommodityList = result.getContent().stream().map(oftenBuyCommodity -> {
            OftenBuyCommodityResponse oftenBuyCommodityResponse = new OftenBuyCommodityResponse();
            oftenBuyCommodityResponse.setId(oftenBuyCommodity.getId());
            oftenBuyCommodityResponse.setShopId(oftenBuyCommodity.getShopId());
            oftenBuyCommodityResponse.setBuyCount(oftenBuyCommodity.getBuyCount());

            //获取商品信息
            CommodityUnitPriceAndPic commodityUnitPriceAndPic = oftenBuyCommodity.getCommoditySku();
            if (commodityUnitPriceAndPic != null) {
                //定义商品sku实体
                OftenBuyCommoditySkuResponse oftenBuyCommoditySkuResponse = new OftenBuyCommoditySkuResponse();
                Commodity commodity = commodityUnitPriceAndPic.getCommodity();
                //商品属性
                List<CommodityGoodsAttribute> attributeAndValueList = commodityUnitPriceAndPic.getAttributeAndValueList();
                String attribute = StringUtils.join(attributeAndValueList.stream().map(commodityAttribute -> commodityAttribute.getCustomerAttributeValue().getValue()).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR);
                if (StringUtils.isNotEmpty(attribute)) {
                    oftenBuyCommoditySkuResponse.setName(commodity.getName() + Constants.COMMODITY_NAME_SPLIT_STR + attribute);
                } else {
                    oftenBuyCommoditySkuResponse.setName(commodity.getName());
                }
                oftenBuyCommoditySkuResponse.setId(commodityUnitPriceAndPic.getId());
                oftenBuyCommoditySkuResponse.setCommodityId(commodity.getId());
                oftenBuyCommoditySkuResponse.setName(commodity.getName());
                oftenBuyCommoditySkuResponse.setPriceType(commodity.getPriceType());
                oftenBuyCommoditySkuResponse.setCommodityPic(commodityUnitPriceAndPic.getCommodityPic());
                oftenBuyCommoditySkuResponse.setUnitPrice(commodityUnitPriceAndPic.getUnitPrice());
                oftenBuyCommoditySkuResponse.setMinOrder(commodity.getMinOrder());
                oftenBuyCommoditySkuResponse.setMemberId(commodity.getMemberId());
                oftenBuyCommoditySkuResponse.setMemberName(commodity.getMemberName());
                oftenBuyCommoditySkuResponse.setMemberRoleId(commodity.getMemberRoleId());
                oftenBuyCommoditySkuResponse.setMemberRoleName(commodity.getMemberRoleName());
                oftenBuyCommodityResponse.setCommoditySku(oftenBuyCommoditySkuResponse);
                //上架商城
                List<CommodityShop> commodityShopList = commodity.getCommodityShopList();
                if (commodityShopList != null && commodityShopList.size() > 0) {
                    List<Long> commodityShopIdList = commodityShopList.stream().map(CommodityShop::getShopId).collect(Collectors.toList());
                    if (commodityShopIdList.size() > 0 && commodityShopIdList.contains(shopId)) {
                        oftenBuyCommodityResponse.setIsPublish(true);
                    }
                }
                return oftenBuyCommodityResponse;
            } else {
                return null;
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());

        return new PageData<>(result.getTotalElements(), oftenBuyCommodityList);
    }

    /**
     * 构建查询条件(查询常购清单列表)
     */
    private Specification<OftenBuyCommodity> getOftenBuyCommodityListSpecification(Long shopId, String name, UserLoginCacheDTO sysUser) {
        return (Specification<OftenBuyCommodity>) (root, query, criteriaBuilder) -> {
            Long memberId = sysUser.getMemberId();
            Long memberRoleId = sysUser.getMemberRoleId();

            Predicate finalConditions = criteriaBuilder.conjunction();

            //商品名称
            if (!StringUtils.isEmpty(name)) {
                Predicate predicate = criteriaBuilder.like(root.get("commoditySku").get("commodity").get("name").as(String.class), "%" + name + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //商城id
            if (shopId != null && shopId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("shopId").as(Long.class), shopId));
            }

            //会员id
            if (memberId != null && memberId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberId").as(Long.class), memberId));
            }

            //会员角色id
            if (memberRoleId != null && memberRoleId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberRoleId").as(Long.class), memberRoleId));
            }

            //排序
            Order idOrder = criteriaBuilder.desc(root.get("buyCount"));

            return query.where(finalConditions).orderBy(idOrder).getRestriction();
        };
    }

    /**
     * 构建查询条件(查询价格策略列表)
     *
     * @param unitPriceStrategyRequest
     * @return
     */
    private Specification<CommodityUnitPriceStrategy> getCommodityUnitPriceStrategySpecification(UserLoginCacheDTO sysUser, UnitPriceStrategyRequest unitPriceStrategyRequest) {
        return (Specification<CommodityUnitPriceStrategy>) (root, query, criteriaBuilder) -> {
            Long memberId = sysUser.getMemberId();
            Long memberRoleId = sysUser.getMemberRoleId();
            String name = unitPriceStrategyRequest.getName();
            String commodityName = unitPriceStrategyRequest.getCommodityName();
            Long brandId = unitPriceStrategyRequest.getBrandId();
            Long customerCategoryId = unitPriceStrategyRequest.getCustomerCategoryId();
            Integer priceType = unitPriceStrategyRequest.getPriceType();
            Double max = unitPriceStrategyRequest.getMax();
            Double min = unitPriceStrategyRequest.getMin();

            Predicate finalConditions = criteriaBuilder.conjunction();

            //价格策略名称
            if (!StringUtils.isEmpty(name)) {
                Predicate predicate = criteriaBuilder.like(root.get("name").as(String.class), "%" + name + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //商品名称/商品编号
            if (!StringUtils.isEmpty(commodityName)) {
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("commodity").get("code").as(String.class), "%" + commodityName + "%"), criteriaBuilder.like(root.get("commodity").get("name").as(String.class), "%" + commodityName + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //品牌
            if (brandId != null && brandId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("commodity").get("brand").as(Brand.class), brandId));
            }

            //会员品类
            if (customerCategoryId != null && customerCategoryId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("commodity").get("customerCategory").as(CustomerCategory.class), customerCategoryId));
            }

            //产品定价
            if (priceType != null && priceType > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("priceType"), priceType));
            }

            //会员id
            if (memberId != null && memberId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberId").as(Long.class), memberId));
            }

            //会员角色id
            if (memberRoleId != null && memberRoleId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberRoleId").as(Long.class), memberRoleId));
            }

            //价格-积分
            if (min != null && min > 0 && max != null && max > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.and(criteriaBuilder.ge(root.get("max"), min), criteriaBuilder.le(root.get("min"), max)));
            } else {
                if (min != null && min > 0) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("max"), min));
                }
                if (max != null && max > 0) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("min"), max));
                }
            }

            //排序
            Order idOrder = criteriaBuilder.desc(root.get("id"));

            return query.distinct(true).where(finalConditions).orderBy(idOrder).getRestriction();
        };
    }

    /**
     * 构建查询条件(查商品详情)
     *
     * @param commodityDetailRequest
     * @return
     */
    private Specification<CommodityUnitPriceAndPic> getCommodityDetailSpecification(CommodityDetailRequest commodityDetailRequest, Long loginMemberId, Long loginMemberRoleId) {
        return (Specification<CommodityUnitPriceAndPic>) (root, query, criteriaBuilder) -> {
            Long productId = commodityDetailRequest.getProductId();
            List<Long> idInList = commodityDetailRequest.getIdInList();
            List<Long> idNotInList = commodityDetailRequest.getIdNotInList();
            List<Long> shopIdList = commodityDetailRequest.getShopIdList();
            Integer shopType = commodityDetailRequest.getShopType();
            Integer shopEnvironment = commodityDetailRequest.getEnvironment();
            List<Integer> statusList = commodityDetailRequest.getStatusList();
            String name = commodityDetailRequest.getName();
            Long customerCategoryId = commodityDetailRequest.getCustomerCategoryId();
            Long categoryId = commodityDetailRequest.getCategoryId();
            Long brandId = commodityDetailRequest.getBrandId();
            List<Integer> priceTypeList = commodityDetailRequest.getPriceTypeList();
            Double max = commodityDetailRequest.getMax();
            Double min = commodityDetailRequest.getMin();
            Long memberId = commodityDetailRequest.getMemberId();
            String memberName = commodityDetailRequest.getMemberName();
            Long memberRoleId = commodityDetailRequest.getMemberRoleId();
            Boolean isMorePrice = commodityDetailRequest.getIsMorePrice();
            Boolean isCrossBorder = commodityDetailRequest.getIsCrossBorder();

            Predicate finalConditions = criteriaBuilder.conjunction();

            List<String> attributeNameList = new ArrayList<>();
            if (StringUtils.isNotEmpty(name)) {
                if (name.contains(Constants.COMMODITY_NAME_SPLIT_STR)) {
                    String[] split = name.split(Constants.COMMODITY_NAME_SPLIT_STR);
                    name = split[0];
                    attributeNameList = Arrays.stream(split).collect(Collectors.toList());
                    attributeNameList.remove(0);
                }
            }
            //商品id
            if (productId != null && productId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("id").as(Long.class), productId));
            }
            //id筛选
            if (idInList != null && !idInList.isEmpty()) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("id")).value(idInList));
            }

            //排除id
            if (idNotInList != null && !idNotInList.isEmpty()) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.not(criteriaBuilder.in(root.get("id")).value(idNotInList)));
            }

            //属性值
            if (!attributeNameList.isEmpty()) {
                for (String attributeName : attributeNameList) {
                    Join join = root.join(root.getModel().getList("attributeAndValueList", CommodityGoodsAttribute.class), JoinType.LEFT);
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(join.get("customerAttributeValue").get("value"), attributeName));
                }
            }

            //状态
            if (statusList != null && !statusList.isEmpty()) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("commodity").get("status")).value(statusList));
            }

            //产品定价
            if (priceTypeList != null && !priceTypeList.isEmpty()) {
                if (loginMemberId != null && loginMemberId > 0) {
                    //有设置价格策略的商品过滤
                    Predicate isUnitPriceStrategy = criteriaBuilder.equal(root.get("commodity").get("isUnitPriceStrategy"), true);
//                    Predicate memberIdPredicate = criteriaBuilder.equal(root.join("commodity").join("unitPriceStrategyList", JoinType.LEFT).join("commodityMemberList", JoinType.LEFT).get("memberId"), loginMemberId);
//                    Predicate memberRoleIdPredicate = criteriaBuilder.equal(root.join("commodity").join("unitPriceStrategyList", JoinType.LEFT).join("commodityMemberList", JoinType.LEFT).get("memberRoleId"), loginMemberRoleId);
                    Predicate enablePredicate = criteriaBuilder.equal(root.join("commodity").join("unitPriceStrategyList", JoinType.LEFT).get("isEnable"), true);
                    Predicate pricePredicate = criteriaBuilder.and(isUnitPriceStrategy, enablePredicate, criteriaBuilder.in(root.join("commodity").join("unitPriceStrategyList", JoinType.LEFT).get("priceType")).value(priceTypeList));
//                    Predicate pricePredicate = criteriaBuilder.and(isUnitPriceStrategy, memberIdPredicate, memberRoleIdPredicate, enablePredicate, criteriaBuilder.in(root.join("commodity").join("unitPriceStrategyList", JoinType.LEFT).get("priceType")).value(priceTypeList));

                    //没有设置价格策略的商品过滤
                    Predicate notPricePredicate = criteriaBuilder.and(criteriaBuilder.in(root.get("commodity").get("priceType")).value(priceTypeList), criteriaBuilder.equal(root.get("commodity").get("isUnitPriceStrategy"), false));
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.or(pricePredicate, notPricePredicate));
                } else {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("commodity").get("priceType")).value(priceTypeList));
                }
            }

            //关键字查询(商品名称,商品编号)
            if (!StringUtils.isEmpty(name)) {
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("commodity").get("code").as(String.class), "%" + name + "%"), criteriaBuilder.like(root.get("commodity").get("name").as(String.class), "%" + name + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //供应会员
            if (!StringUtils.isEmpty(memberName)) {
                Predicate predicate = criteriaBuilder.like(root.get("commodity").get("memberName").as(String.class), "%" + memberName + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //会员品类
            if (customerCategoryId != null && customerCategoryId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("commodity").get("customerCategory").as(CustomerCategory.class), customerCategoryId));
            }
            //平台后台品类
            if (categoryId != null && categoryId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("commodity").get("customerCategory").get("category").as(Category.class), categoryId));
            }

            //品牌
            if (brandId != null && brandId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("commodity").get("brand").as(Brand.class), brandId));
            }

            //是否需要查询阶梯价格
            if (isMorePrice != null && !isMorePrice) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("isMorePrice"), false));
            }

            //商城id
            if (shopIdList != null && shopIdList.size() > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.join("commodity").join("commodityShopList").get("shopId")).value(shopIdList));
            }

            //商城类型
            if (shopType != null && shopType > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.join("commodity").join("commodityShopList").get("type").as(Integer.class), shopType));
            }

            //商城环境
            if (shopEnvironment != null && shopEnvironment > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.join("commodity").join("commodityShopList").get("environment").as(Integer.class), shopEnvironment));
            }

            //会员id
            if (memberId != null && memberId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("commodity").get("memberId").as(Long.class), memberId));
            }

            //会员角色id
            if (memberRoleId != null && memberRoleId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("commodity").get("memberRoleId").as(Long.class), memberRoleId));
            }

            //是否跨境商品
            if (isCrossBorder != null) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("commodity").get("isCrossBorder"), isCrossBorder));
            }

            //价格-积分
            if (min != null && min > 0 && max != null && max > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.and(criteriaBuilder.ge(root.get("commodity").get("max"), min), criteriaBuilder.le(root.get("commodity").get("min"), max)));
            } else {
                if (min != null && min > 0) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("commodity").get("max"), min));
                }
                if (max != null && max > 0) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("commodity").get("min"), max));
                }
            }

            //排序
            Order idOrder = criteriaBuilder.desc(root.get("id"));

            return query.distinct(true).where(finalConditions).orderBy(idOrder).getRestriction();
        };
    }

    /**
     * 构建查询条件
     *
     * @param commodityQueryRequest
     * @return
     */
    private Specification<Commodity> getSpecification(CommodityQueryRequest commodityQueryRequest) {
        return (Specification<Commodity>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();
            Long productId = commodityQueryRequest.getProductId();
            Long memberId = commodityQueryRequest.getMemberId();
            String memberName = commodityQueryRequest.getMemberName();
            Long memberRoleId = commodityQueryRequest.getMemberRoleId();
            String memberRoleName = commodityQueryRequest.getMemberRoleName();
            String name = commodityQueryRequest.getName();
            Long brandId = commodityQueryRequest.getBrandId();
            String brandName = commodityQueryRequest.getBrandName();
            Long customerCategoryId = commodityQueryRequest.getCustomerCategoryId();
            String customerCategoryName = commodityQueryRequest.getCustomerCategoryName();
            Long categoryId = commodityQueryRequest.getCategoryId();
            Double max = commodityQueryRequest.getMax();
            Double min = commodityQueryRequest.getMin();
            Long shopId = commodityQueryRequest.getShopId();
            Integer type = commodityQueryRequest.getType();
            Integer environment = commodityQueryRequest.getEnvironment();
            Integer checkType = commodityQueryRequest.getCheckType();
            Integer commodityType = commodityQueryRequest.getCommodityType();

            List<Integer> priceTypeList = commodityQueryRequest.getPriceTypeList();
            List<Integer> statusList = commodityQueryRequest.getStatusList();
            List<Long> idNotList = commodityQueryRequest.getIdNotList();
            List<Long> idList = commodityQueryRequest.getIdList();
            List<Long> parentMemberIdList = commodityQueryRequest.getParentMemberIdList();
            List<Long> parentMemberRoleIds = commodityQueryRequest.getParentMemberRoleIds();
            //商品id
            if (productId != null && productId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("id"), productId));
            }

            if (idNotList != null && !idNotList.isEmpty()) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.not(criteriaBuilder.in(root.get("id")).value(idNotList)));
            }

            if (idList != null && !idList.isEmpty()) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("id")).value(idList));
            }

            //关键字查询(商品名称,商品编号)
            if (!StringUtils.isEmpty(name)) {
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("code").as(String.class), "%" + name + "%"), criteriaBuilder.like(root.get("name").as(String.class), "%" + name + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //产品定价
            if (priceTypeList != null && !priceTypeList.isEmpty()) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("priceType")).value(priceTypeList));
            }

            //商品类型
            if (commodityType != null && commodityType > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("type")).value(commodityType));
            }

            //会员品类
            if (customerCategoryId != null && customerCategoryId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("customerCategory").as(CustomerCategory.class), customerCategoryId));
            }
            if (!StringUtils.isEmpty(customerCategoryName)) {
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("customerCategory").get("name").as(String.class), "%" + customerCategoryName + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //平台后台品类
            if (categoryId != null && categoryId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("customerCategory").get("category").as(Category.class), categoryId));
            }

            //品牌
            if (brandId != null && brandId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("brand").as(Brand.class), brandId));
            }
            if (!StringUtils.isEmpty(brandName)) {
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("brand").get("name").as(String.class), "%" + brandName + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //商城环境
            if (shopId != null && shopId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.join("commodityShopList").get("shopId"), shopId));
            }
            if (type != null && type > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.join("commodityShopList").get("type"), type));
            }
            if (environment != null && environment > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.join("commodityShopList").get("environment"), environment));
            }

            //上级会员id
            if (parentMemberIdList != null && !parentMemberIdList.isEmpty()) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("memberId")).value(parentMemberIdList));
            }

            //上级会员角色id
            if (!CollectionUtils.isEmpty(parentMemberRoleIds)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("memberRoleId")).value(parentMemberRoleIds));
            }

            //会员id
            if (memberId != null && memberId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberId"), memberId));
            }
            if (StringUtils.isNotEmpty(memberName)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberName"), memberName));
            }

            //会员角色id
            if (memberRoleId != null && memberRoleId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberRoleId"), memberRoleId));
            }
            if (StringUtils.isNotEmpty(memberRoleName)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberRoleName"), memberRoleName));
            }

            //状态
            if (statusList != null && !statusList.isEmpty()) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("status")).value(statusList));
            }
            //价格-积分
            if (min != null && min > 0 && max != null && max > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.and(criteriaBuilder.ge(root.get("max"), min), criteriaBuilder.le(root.get("min"), max)));
            } else {
                if (min != null && min > 0) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("max"), min));
                }
                if (max != null && max > 0) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("min"), max));
                }
            }
            //审核类型
            if (checkType != null) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("checkType"), checkType));
            }

            //排序
            Order idOrder = criteriaBuilder.desc(root.get("id"));
            Order applyTimeOrder = criteriaBuilder.desc(root.get("applyTime"));
            Order checkTimeOrder = criteriaBuilder.desc(root.get("checkTime"));
            Order publishTimeOrder = criteriaBuilder.desc(root.get("publishTime"));

            return query.distinct(true).orderBy(idOrder, applyTimeOrder, checkTimeOrder, publishTimeOrder).where(finalConditions).getRestriction();
        };
    }

    /**
     * 查询商品列表 -- 平台后台
     *
     * @param pageVO
     * @param commodityQueryRequest
     * @return Page<Attribute>
     */
    @Override
    public Page<Commodity> getPlatformCommodityList(PageVO pageVO, CommodityQueryRequest commodityQueryRequest) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return commodityRepository.findAll(getSpecification(commodityQueryRequest), page);
    }

    /**
     * 审核--平台后台
     *
     * @param id
     * @return
     */
    @Override
    public String checkCommodity(UserLoginCacheDTO sysUser, Long id, Integer status, String checkRemark) {
        //先判断是否是成功或者不通过状态
        if (!CommodityStatusEnum.Not_Pass.getCode().equals(status) && !CommodityStatusEnum.Pass.getCode().equals(status)) {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_STATUS_UNLEGAL);
        }
        //验证数据库中是否存在该数据
        Commodity commodity = commodityRepository.findById(id).orElse(null);
        if (commodity != null) {
            Integer current_status = commodity.getStatus();
            if (!CommodityStatusEnum.Not_Check.getCode().equals(current_status)) {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_STATUS_UNLEGAL);
            }
            //持久化数据
            if (CommodityStatusEnum.Pass.getCode().equals(status)) {
                commodity.setIsUpdateAttribute(false);
            }
            commodity.setStatus(status);
            commodity.setCheckTime(System.currentTimeMillis());
            commodityRepository.saveAndFlush(commodity);

            CommodityCheckRecord commodityCheckRecord = new CommodityCheckRecord();
            commodityCheckRecord.setMemberRoleId(sysUser.getMemberRoleId());
            commodityCheckRecord.setMemberRoleName(sysUser.getMemberRoleName());
            commodityCheckRecord.setOperation(OperationEnum.Check.getCode());
            commodityCheckRecord.setStatus(status);
            commodityCheckRecord.setCheckRemark(checkRemark);
            commodityCheckRecord.setCreateTime(System.currentTimeMillis());
            commodityCheckRecord.setCommodityId(commodity.getId());
            commodityCheckRecordRepository.saveAndFlush(commodityCheckRecord);

            try {
                List<OperateNoticeVO> operateNoticeVOList = new ArrayList<>();
                SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
                //先判断是否是成功或者不通过状态--首页数据统计
                if (CommodityStatusEnum.Pass.getCode().equals(status)) {
                    //审核通过会员待上架商品+1
                    OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                    operateNoticeVO.setMemberId(commodity.getMemberId());
                    operateNoticeVO.setRoleId(commodity.getMemberRoleId());
                    operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                    operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_PUBLISH.getCode());
                    operateNoticeVO.setIncreaseCount(1L);
                    operateNoticeVOList.add(operateNoticeVO);
                    //审核结果
                    systemMessageRequest.setParams(Arrays.asList(commodity.getName(), CheckStatusEnum.AGREE.getMessage()));
                } else {
                    //审核结果
                    systemMessageRequest.setParams(Arrays.asList(commodity.getName(), CheckStatusEnum.REFUSE.getMessage()));
                }
                //平台后台待审核商品-1
                OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                operateNoticeVO.setMemberId(0L);
                operateNoticeVO.setRoleId(0L);
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.TO_BE_PRODUCT_CHECK_COMMIT.getCode());
                operateNoticeVO.setReduceCount(1L);
                operateNoticeVOList.add(operateNoticeVO);
                reportControllerFeign.addOperateNoticeList(operateNoticeVOList);

                //发送消息
                systemMessageRequest.setMessageNotice(MessageTemplateCode.commodity_audit);
                systemMessageRequest.setMemberId(commodity.getMemberId());
                systemMessageRequest.setRoleId(commodity.getMemberRoleId());
                systemMessageControllerFeign.sendSystemMessage(systemMessageRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ResponseCode.SUCCESS.getMessage();
        } else {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
        }
    }

    /**
     * 查询商品审核记录--平台后台
     *
     * @return List<CommodityCheckRecord>
     */
    @Override
    public List<CommodityCheckRecord> getCommodityCheckRecord(Long commodityId) {
        return commodityCheckRecordRepository.findByCommodityIdOrderByCreateTime(commodityId);
    }

    /**
     * 查询商品审核记录--平台后台
     *
     * @return List<CommodityCheckRecord>
     */
    @Override
    public Page<CommodityCheckRecord> getCommodityCheckRecordList(PageVO pageVO, Long commodityId, Long startTime, Long endTime) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return commodityCheckRecordRepository.findAll(getCommodityCheckRecordSpecification(commodityId, startTime, endTime), page);
    }

    /**
     * 构建查询条件
     */
    private Specification<CommodityCheckRecord> getCommodityCheckRecordSpecification(Long commodityId, Long startTime, Long endTime) {
        return (Specification<CommodityCheckRecord>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            if (commodityId != null && commodityId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("commodityId"), commodityId));
            }

            if (startTime != null && startTime > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("createTime"), startTime));
            }

            if (endTime != null && endTime > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("createTime"), endTime));
            }

            //排序
            Order idOrder = criteriaBuilder.desc(root.get("id"));

            return query.orderBy(idOrder).where(finalConditions).getRestriction();
        };
    }

    /**
     * 查询商品是否用到运费模板
     *
     * @param id 运费模板id
     * @return
     */
    @Override
    public Boolean getCommodityUseTemplate(Long id) {
        Integer count = commodityRepository.findCommodityCountByLogisticsTemplateId(String.valueOf(id));
        return count != null && count > 0;
    }

    /**
     * 查询商品是否用到发货地址
     *
     * @param id 发货地址id
     * @return
     */
    @Override
    public Boolean getCommodityUseSendAddress(Long id) {
        Integer count = commodityRepository.findCommodityCountByLogisticsSendAddressId(String.valueOf(id));
        return count != null && count > 0;
    }

    /**
     * 查询商品是否用到物流公司
     *
     * @param id 物流公司id
     * @return
     */
    @Override
    public Boolean getCommodityUseCompany(Long id) {
        Integer count = commodityRepository.findCommodityCountByLogisticsCompanyId(String.valueOf(id));
        return count != null && count > 0;
    }

    /**
     * 查询商品是否用到单位
     *
     * @param id 单位id
     * @return
     */
    @Override
    public Boolean getCommodityUseUnit(Long id) {
        return commodityRepository.existsByUnitId(id);
    }

    /**
     * 查询商品sku规格名称
     *
     * @param id 商品skuId
     * @return
     */
    @Override
    public CommodityUnitPriceAndPic getCommodityBySkuId(Long id) {
        return commodityUnitPriceAndPicRepository.findById(id).orElse(null);
    }

    /**
     * 查询商品sku对应的库存
     *
     * @param memberId
     * @param memberRoleId
     * @param commoditySkuIdList
     * @return
     */
    @Override
    public List<CommoditySkuStockResponse> getCommoditySkuStock(Long memberId, Long memberRoleId, Long shopId, List<Long> commoditySkuIdList) {
        //组装redis键值格式
        List<HashMap<String, String[]>> keyFieldList = commoditySkuIdList.stream().map(commoditySkuIdId -> {
            HashMap<String, String[]> map = new HashMap<>();
            String unitPriceAndPicId = CommonConstant.FREIGHT_SPACE_REDIS_KEY + shopId + "_" + commoditySkuIdId;
            String commodityMemberId = String.valueOf(memberId);
            map.put(unitPriceAndPicId, new String[]{commodityMemberId, CommonConstant.FREIGHT_All});
            return map;
        }).collect(Collectors.toList());

        //获取库存数据并赋值
        List<Object> resultList = redisStringUtils.hMGetBatch(keyFieldList, Constants.REDIS_PRODUCT_INDEX);

        //组装数据
        List<CommoditySkuStockResponse> commoditySkuStockList = new ArrayList<>();
        if (commoditySkuIdList.size() > 0) {
            for (int i = 0; i < commoditySkuIdList.size(); i++) {
                Long commoditySkuId = commoditySkuIdList.get(i);
                //计算当前商品的库存数
                List<String> stockList = (List<String>) resultList.get(i);
                if (stockList != null && !stockList.isEmpty()) {
                    CommoditySkuStockResponse commoditySkuStockResponse = new CommoditySkuStockResponse();
                    commoditySkuStockResponse.setCommoditySkuId(commoditySkuId);
                    List<String> collect = stockList.stream().filter(StrUtil::isNotEmpty).collect(Collectors.toList());
                    if (!collect.isEmpty()) {
                        Double stockCount = collect.stream().map(Double::parseDouble).reduce(Double::sum).get();
                        commoditySkuStockResponse.setStock(stockCount);
                    } else {
                        commoditySkuStockResponse.setStock(0d);
                    }
                    commoditySkuStockList.add(commoditySkuStockResponse);
                }
            }
        }
        return commoditySkuStockList;
    }

    /**
     * 查询商品sku列表
     *
     * @param pageVO                 分页实体
     * @param commodityDetailRequest 查询条件实体
     * @return
     */
    @Override
    public PageData<CommoditySkuResponse> getCommoditySkuListByShopId(PageVO pageVO, CommodityDetailRequest commodityDetailRequest) {
        Long memberId = commodityDetailRequest.getMemberId();
        Long memberRoleId = commodityDetailRequest.getMemberRoleId();
        List<Long> shopIdList = commodityDetailRequest.getShopIdList();

        List<CommoditySkuResponse> commoditySkuResponseList = new ArrayList<>();
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Page<CommodityUnitPriceAndPic> list = commodityUnitPriceAndPicRepository.findAll(getCommodityDetailSpecification(commodityDetailRequest, null, null), page);
        List<CommodityUnitPriceAndPic> commodityUnitPriceAndPicList = list.getContent();
        if(!CollectionUtils.isEmpty(commodityUnitPriceAndPicList)){
            //查询当前登录用户的所有上级对应的会员等级
            Map<String, Integer> memberLevelMap = new HashMap<>();
            MemberFeignVO memberFeignVO = new MemberFeignVO();
            memberFeignVO.setMemberId(memberId);
            memberFeignVO.setRoleId(memberRoleId);
            Wrapper<List<MemberFeignLevelDetailVO>> subMemberLevels = memberLevelRightCreditControllerFeign.findSubMemberLevels(memberFeignVO);
            if(subMemberLevels != null && ResponseCode.SUCCESS.getCode() == subMemberLevels.getCode()){
                List<MemberFeignLevelDetailVO> data = subMemberLevels.getData();
                if(!CollectionUtils.isEmpty(data)){
                    data.stream().filter(memberFeignLevelDetailVO -> memberFeignLevelDetailVO.getRelType() == 1).forEach(memberFeignLevelDetailVO -> {
                        Long upperMemberId = memberFeignLevelDetailVO.getUpperMemberId();
                        Long upperRoleId = memberFeignLevelDetailVO.getUpperRoleId();
                        Integer level = memberFeignLevelDetailVO.getLevel();
                        memberLevelMap.put(upperMemberId + Constants.UNDERLINE_STR + upperRoleId, level);
                    });
                }
            }
            for (CommodityUnitPriceAndPic commodityUnitPriceAndPic : commodityUnitPriceAndPicList) {
                Commodity commodity = commodityUnitPriceAndPic.getCommodity();
                CommoditySkuResponse commoditySkuResponse = new CommoditySkuResponse();
                commoditySkuResponse.setCommodityId(commodity.getId());
                commoditySkuResponse.setId(commodityUnitPriceAndPic.getId());
                commoditySkuResponse.setCode(Constants.COMMODITY_CODE_PREFIX + CodeUtils.digits32(commodityUnitPriceAndPic.getId(), Constants.CODE_NUM));
                commoditySkuResponse.setUnitName(commodity.getUnitName());
                commoditySkuResponse.setPriceType(commodity.getPriceType());
                commoditySkuResponse.setCustomerCategoryName(commodity.getCustomerCategory().getName());
                if (commodity.getBrand() != null) {
                    commoditySkuResponse.setBrandName(commodity.getBrand().getName());
                }

                //商品价格
                Map<String, Double> unitPrice = commodityUnitPriceAndPic.getUnitPrice();
                if (unitPrice != null && unitPrice.size() > 0) {
                    commoditySkuResponse.setUnitPrice(unitPrice);
                }

                //如果存在价格策略设置的价格
                Integer loginMemberLevel = memberLevelMap.get(commodity.getMemberId() + Constants.UNDERLINE_STR + commodity.getMemberRoleId());
                Map<String, Double> strategyPrice = this.getStrategyPrice(commodityUnitPriceAndPic, shopIdList, memberId, memberRoleId, loginMemberLevel == null ? 0 : loginMemberLevel);
                if (strategyPrice != null && strategyPrice.size() > 0) {
                    commoditySkuResponse.setUnitPrice(strategyPrice);
                }

                //商品属性
                List<CommodityGoodsAttribute> attributeAndValueList = commodityUnitPriceAndPic.getAttributeAndValueList();
                String attribute = StringUtils.join(attributeAndValueList.stream().sorted(Comparator.comparing(CommodityGoodsAttribute::getId).reversed()).map(commodityGoodsAttribute -> commodityGoodsAttribute.getCustomerAttributeValue().getValue()).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR);
                if (StringUtils.isNotEmpty(attribute)) {
                    commoditySkuResponse.setName(commodity.getName() + Constants.COMMODITY_NAME_SPLIT_STR + attribute);
                } else {
                    commoditySkuResponse.setName(commodity.getName());
                }
                commoditySkuResponse.setMainPic(commodity.getMainPic());
                commoditySkuResponse.setMinOrder(commodity.getMinOrder());
                commoditySkuResponseList.add(commoditySkuResponse);
            }
        }
        return new PageData<>(list.getTotalElements(), commoditySkuResponseList);
    }

    /**
     * 获取价格策略中设置的价格
     *
     * @param commodityUnitPriceAndPic 商品sku
     * @param shopIdList               商城id数组
     * @param loginMemberId                 会员id
     * @param loginMemberRoleId             会员角色id
     * @param loginMemberLevel             会员角色id
     */
    private Map<String, Double> getStrategyPrice(CommodityUnitPriceAndPic commodityUnitPriceAndPic, List<Long> shopIdList, Long loginMemberId, Long loginMemberRoleId, Integer loginMemberLevel) {
        boolean flag = true;
        Map<String, Double> strategyPrice = new HashMap<>();
        List<CommodityUnitPriceStrategy> unitPriceStrategyList = commodityUnitPriceAndPic.getCommodity().getUnitPriceStrategyList();
        for (CommodityUnitPriceStrategy commodityUnitPriceStrategy : unitPriceStrategyList) {
            Boolean isMember = commodityUnitPriceStrategy.getIsMember();
            Long shopId = commodityUnitPriceStrategy.getShopId();
            Boolean isEnable = commodityUnitPriceStrategy.getIsEnable();
            if (isMember != null && isMember && isEnable && shopIdList.contains(shopId)) {
                Integer applyType = commodityUnitPriceStrategy.getApplyType();
                if(UnitPriceStrategyApplyTypeEnum.Member.getCode().equals(applyType)){
                    //价格策略对应的会员价格
                    List<CommodityMember> commodityMemberList = commodityUnitPriceStrategy.getCommodityMemberList();
                    for (CommodityMember commodityMember : commodityMemberList) {
                        Long priceStrategyMemberId = commodityMember.getMemberId();
                        Long priceStrategyMemberRoleId = commodityMember.getMemberRoleId();
                        if (priceStrategyMemberId.equals(loginMemberId) && priceStrategyMemberRoleId.equals(loginMemberRoleId)) {
                            List<CommodityMemberUnitPrice> memberUnitPriceList = commodityUnitPriceStrategy.getMemberUnitPriceList();
                            for (CommodityMemberUnitPrice commodityMemberUnitPrice : memberUnitPriceList) {
                                Long id = commodityMemberUnitPrice.getCommodityUnitPrice().getId();
                                if (commodityUnitPriceAndPic.getId().equals(id)) {
                                    strategyPrice = commodityMemberUnitPrice.getUnitPrice();
                                    flag = false;
                                }
                            }
                        }
                    }
                }else{
                    //价格策略对应的会员等级价格
                    List<CommodityMemberLevel> commodityMemberLevelList = commodityUnitPriceStrategy.getCommodityMemberLevelList();
                    for (CommodityMemberLevel commodityMemberLevel : commodityMemberLevelList) {
                        Long memberRoleId = commodityMemberLevel.getMemberRoleId();
                        Integer level = commodityMemberLevel.getLevel();
                        if (memberRoleId.equals(loginMemberRoleId) && level.equals(loginMemberLevel)) {
                            List<CommodityMemberUnitPrice> memberUnitPriceList = commodityUnitPriceStrategy.getMemberUnitPriceList();
                            for (CommodityMemberUnitPrice commodityMemberUnitPrice : memberUnitPriceList) {
                                Long id = commodityMemberUnitPrice.getCommodityUnitPrice().getId();
                                if (commodityUnitPriceAndPic.getId().equals(id)) {
                                    strategyPrice = commodityMemberUnitPrice.getUnitPrice();
                                    flag = false;
                                }
                            }
                        }
                    }
                }
            }
        }
        //价格策略对应的商城价格(如果存在会员价格，则不覆盖)
        if (flag) {
            for (CommodityUnitPriceStrategy commodityUnitPriceStrategy : unitPriceStrategyList) {
                Boolean isMember = commodityUnitPriceStrategy.getIsMember();
                Long shopId = commodityUnitPriceStrategy.getShopId();
                Boolean isEnable = commodityUnitPriceStrategy.getIsEnable();
                if (isMember != null && !isMember && isEnable && shopIdList.contains(shopId)) {
                    List<CommodityMemberUnitPrice> memberUnitPriceList = commodityUnitPriceStrategy.getMemberUnitPriceList();
                    for (CommodityMemberUnitPrice commodityMemberUnitPrice : memberUnitPriceList) {
                        Long id = commodityMemberUnitPrice.getCommodityUnitPrice().getId();
                        if (commodityUnitPriceAndPic.getId().equals(id)) {
                            strategyPrice = commodityMemberUnitPrice.getUnitPrice();
                        }
                    }
                }
            }
        }
        return strategyPrice;
    }

    /**
     * 查询商品列表--平台(全部商品)
     *
     * @param pageVO                 分页实体
     * @param commodityDetailRequest 查询条件实体
     * @return
     */
    @Override
    public PageData<CommonCommodityPlatformResponse> getCommodityListByPlatform(PageVO pageVO, CommodityDetailRequest commodityDetailRequest) {
        List<CommonCommodityPlatformResponse> commodityGoodsResponseList = new ArrayList<>();
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Page<CommodityUnitPriceAndPic> list = commodityUnitPriceAndPicRepository.findAll(getCommodityDetailSpecification(commodityDetailRequest, null, null), page);
        List<CommodityUnitPriceAndPic> commodityUnitPriceAndPicList = list.getContent();
        if (!commodityUnitPriceAndPicList.isEmpty()) {
            for (CommodityUnitPriceAndPic commodityUnitPriceAndPic : commodityUnitPriceAndPicList) {
                Long commodityUnitPriceAndPicId = commodityUnitPriceAndPic.getId();
                Commodity commodity = commodityUnitPriceAndPic.getCommodity();
                CommonCommodityPlatformResponse commodityGoodsResponse = new CommonCommodityPlatformResponse();
                commodityGoodsResponse.setCommodityId(commodity.getId());
                commodityGoodsResponse.setId(commodityUnitPriceAndPicId);
                commodityGoodsResponse.setCode(Constants.COMMODITY_CODE_PREFIX + CodeUtils.digits32(commodityUnitPriceAndPic.getId(), Constants.CODE_NUM));
                commodityGoodsResponse.setPriceType(commodity.getPriceType());
                commodityGoodsResponse.setStatus(commodity.getStatus());
                commodityGoodsResponse.setCustomerCategoryName(commodity.getCustomerCategory().getName());
                if (commodity.getBrand() != null) {
                    commodityGoodsResponse.setBrandName(commodity.getBrand().getName());
                }
                //商品属性
                List<CommodityGoodsAttribute> attributeAndValueList = commodityUnitPriceAndPic.getAttributeAndValueList();
                String attribute = StringUtils.join(attributeAndValueList.stream().sorted(Comparator.comparing(CommodityGoodsAttribute::getId).reversed()).map(commodityGoodsAttribute -> commodityGoodsAttribute.getCustomerAttributeValue().getValue()).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR);
                if (StringUtils.isNotEmpty(attribute)) {
                    commodityGoodsResponse.setName(commodity.getName() + Constants.COMMODITY_NAME_SPLIT_STR + attribute);
                } else {
                    commodityGoodsResponse.setName(commodity.getName());
                }
                commodityGoodsResponse.setStatus(commodity.getStatus());
                commodityGoodsResponse.setMemberId(commodity.getMemberId());
                commodityGoodsResponse.setMemberName(commodity.getMemberName());
                commodityGoodsResponse.setMemberRoleId(commodity.getMemberRoleId());
                commodityGoodsResponse.setMemberRoleName(commodity.getMemberRoleName());
                commodityGoodsResponse.setMainPic(commodity.getMainPic());
                commodityGoodsResponse.setUnitName(commodity.getUnitName());
                commodityGoodsResponse.setUnitPrice(commodityUnitPriceAndPic.getUnitPrice());
                Category category = commodity.getCustomerCategory().getCategory();
                if (category != null) {
                    commodityGoodsResponse.setCategoryName(category.getName());
                }

                commodityGoodsResponseList.add(commodityGoodsResponse);
            }
        }
        return new PageData<>(list.getTotalElements(), commodityGoodsResponseList);
    }

    /**
     * 查询商品列表--通过会员商品sku集合
     *
     * @param commoditySkuIdList 查询条件实体
     * @return
     */
    @Override
    public List<CommodityGoodsResponse> getCommodityByCommoditySkuIdList(List<Long> commoditySkuIdList) {
        List<CommodityGoodsResponse> commodityGoodsResponseList = new ArrayList<>();
        List<CommodityUnitPriceAndPic> commodityUnitPriceAndPicList = commodityUnitPriceAndPicRepository.findByIdIn(commoditySkuIdList);
        if (commodityUnitPriceAndPicList != null && !commodityUnitPriceAndPicList.isEmpty()) {
            for (CommodityUnitPriceAndPic commodityUnitPriceAndPic : commodityUnitPriceAndPicList) {
                Long commodityUnitPriceAndPicId = commodityUnitPriceAndPic.getId();
                Commodity commodity = commodityUnitPriceAndPic.getCommodity();
                CommodityGoodsResponse commodityGoodsResponse = new CommodityGoodsResponse();
                commodityGoodsResponse.setCommodityId(commodity.getId());
                commodityGoodsResponse.setId(commodityUnitPriceAndPicId);
                commodityGoodsResponse.setIsCrossBorder(commodity.getIsCrossBorder());
                commodityGoodsResponse.setCode(Constants.COMMODITY_CODE_PREFIX + CodeUtils.digits32(commodityUnitPriceAndPic.getId(), Constants.CODE_NUM));
                if (commodityUnitPriceAndPic.getGoods() != null) {
                    commodityGoodsResponse.setGoodsId(commodityUnitPriceAndPic.getGoods().getId());
                }
                commodityGoodsResponse.setUnitName(commodity.getUnitName());
                commodityGoodsResponse.setPriceType(commodity.getPriceType());
                commodityGoodsResponse.setStatus(commodity.getStatus());
                commodityGoodsResponse.setCustomerCategoryName(commodity.getCustomerCategory().getName());
                if (commodity.getBrand() != null) {
                    commodityGoodsResponse.setBrandName(commodity.getBrand().getName());
                }

                //设置商品默认价格
                Map<String, Double> unitPrice = commodityUnitPriceAndPic.getUnitPrice();
                if (unitPrice != null && unitPrice.size() > 0) {
                    commodityGoodsResponse.setMin(Collections.min(unitPrice.values()));
                    commodityGoodsResponse.setMax(Collections.max(unitPrice.values()));
                    commodityGoodsResponse.setUnitPrice(unitPrice);
                }

                //商品属性
                List<CommodityGoodsAttribute> attributeAndValueList = commodityUnitPriceAndPic.getAttributeAndValueList();
                String attribute = StringUtils.join(attributeAndValueList.stream().sorted(Comparator.comparing(CommodityGoodsAttribute::getId).reversed()).map(commodityGoodsAttribute -> commodityGoodsAttribute.getCustomerAttributeValue().getValue()).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR);
                if (StringUtils.isNotEmpty(attribute)) {
                    commodityGoodsResponse.setName(commodity.getName() + Constants.COMMODITY_NAME_SPLIT_STR + attribute);
                } else {
                    commodityGoodsResponse.setName(commodity.getName());
                }
                commodityGoodsResponse.setAttribute(attribute);
                commodityGoodsResponse.setApplyTime(commodity.getApplyTime());
                commodityGoodsResponse.setIsMemberPrice(commodity.getIsMemberPrice());
                commodityGoodsResponse.setStatus(commodity.getStatus());
                commodityGoodsResponse.setMemberId(commodity.getMemberId());
                commodityGoodsResponse.setMemberName(commodity.getMemberName());
                commodityGoodsResponse.setMemberRoleId(commodity.getMemberRoleId());
                commodityGoodsResponse.setMemberRoleName(commodity.getMemberRoleName());

                //商品图片
                String[] commodityPic = commodityUnitPriceAndPic.getCommodityPic();
                if (commodityPic != null && commodityPic.length > 0) {
                    commodityGoodsResponse.setMainPic(commodityPic[0]);
                } else {
                    commodityGoodsResponse.setMainPic(commodity.getMainPic());
                }
                commodityGoodsResponse.setMinOrder(commodity.getMinOrder());
                commodityGoodsResponse.setTaxRate(commodity.getTaxRate());

                Integer type = commodity.getType();
                commodityGoodsResponse.setType(type);
                //上游商品才有值
                if (CommodityTypeEnum.Upper.getCode().equals(type)) {
                    commodityGoodsResponse.setCommodityUnitPriceAndPicId(commodityUnitPriceAndPic.getUpperCommoditySkuId());
                    commodityGoodsResponse.setUpperMemberId(commodity.getUpperMemberId());
                    commodityGoodsResponse.setUpperMemberName(commodity.getUpperMemberName());
                    commodityGoodsResponse.setUpperMemberRoleId(commodity.getUpperMemberRoleId());
                    commodityGoodsResponse.setUpperMemberRoleName(commodity.getUpperMemberRoleName());
                }

                //商品物流信息
                LogisticsResponse logisticsResponse = new LogisticsResponse();
                BeanUtil.copyProperties(commodity.getLogistics(), logisticsResponse);
                commodityGoodsResponse.setLogistics(logisticsResponse);

                //商品所属店铺信息
                commodityGoodsResponse.setStoreId(commodity.getStoreId());
                commodityGoodsResponse.setStoreName(commodity.getStoreName());
                commodityGoodsResponse.setStoreLogo(commodity.getStoreLogo());

                //商品所属区域信息
                commodityGoodsResponse.setIsAllArea(commodity.getIsAllArea());
                if (!commodity.getIsAllArea()) {//若不是全区域则字段有数据
                    List<CommodityArea> commodityAreas = commodity.getCommodityAreaList();
                    List<CommodityAreaResponse> commodityAreaList = commodityAreas.stream().map(commodityArea -> BeanUtil.copyProperties(commodityArea, CommodityAreaResponse.class)).collect(Collectors.toList());
                    commodityGoodsResponse.setCommodityAreaList(commodityAreaList);
                }

                commodityGoodsResponseList.add(commodityGoodsResponse);
            }
        }
        return commodityGoodsResponseList;
    }

    /**
     * 通过商品id集合查询商品
     *
     * @param commodityIdList
     * @return
     */
    @Override
    public List<Commodity> getCommodityByIdList(List<Long> commodityIdList) {
        return commodityRepository.findAllById(commodityIdList);
    }

    /**
     * 查询上游供应会员商品列表--通过商品sku集合
     *
     * @param commoditySkuIdList 查询条件实体
     * @return
     */
    @Override
    public List<UpperCommodityResponse> getUpperCommodityByCommoditySkuIdList(List<Long> commoditySkuIdList) {
        List<UpperCommodityResponse> upperCommodityResponseList = new ArrayList<>();
        CommodityDetailRequest commodityDetailRequest = new CommodityDetailRequest();
        commodityDetailRequest.setIdInList(commoditySkuIdList);
        List<CommodityUnitPriceAndPic> commodityUnitPriceAndPicList = commodityUnitPriceAndPicRepository.findAll(this.getCommodityDetailSpecification(commodityDetailRequest, null, null));
        if (!commodityUnitPriceAndPicList.isEmpty()) {
            Map<Long, Long> commoditySkuMap = commodityUnitPriceAndPicList.stream().collect(Collectors.toMap(CommodityUnitPriceAndPic::getId, CommodityUnitPriceAndPic::getUpperCommoditySkuId));

            //获取上游会员商品skuId
            List<Long> upperCommoditySkuIdList = commodityUnitPriceAndPicList.stream().map(CommodityUnitPriceAndPic::getUpperCommoditySkuId).distinct().collect(Collectors.toList());
            if (upperCommoditySkuIdList.size() > 0) {
                commodityDetailRequest.setIdInList(upperCommoditySkuIdList);
                List<CommodityUnitPriceAndPic> upperCommodityUnitPriceAndPicList = commodityUnitPriceAndPicRepository.findAll(this.getCommodityDetailSpecification(commodityDetailRequest, null, null));
                if (!upperCommodityUnitPriceAndPicList.isEmpty()) {
                    Map<Long, CommodityUnitPriceAndPic> upperCommodityUnitPriceAndPicMap = upperCommodityUnitPriceAndPicList.stream().collect(Collectors.toMap(CommodityUnitPriceAndPic::getId, CommodityUnitPriceAndPic -> CommodityUnitPriceAndPic));

                    for (CommodityUnitPriceAndPic commodityUnitPriceAndPic : commodityUnitPriceAndPicList) {
                        Long commodityUnitPriceAndPicId = commodityUnitPriceAndPic.getId();
                        Long upperCommoditySkuId = commoditySkuMap.get(commodityUnitPriceAndPicId);
                        CommodityUnitPriceAndPic upperCommodityUnitPriceAndPic = upperCommodityUnitPriceAndPicMap.get(upperCommoditySkuId);
                        if (upperCommodityUnitPriceAndPic != null) {
                            Commodity commodity = upperCommodityUnitPriceAndPic.getCommodity();
                            UpperCommodityResponse upperCommodityResponse = new UpperCommodityResponse();
                            upperCommodityResponse.setCommodityId(commodity.getId());
                            upperCommodityResponse.setId(upperCommodityUnitPriceAndPic.getId());
                            upperCommodityResponse.setCode(Constants.COMMODITY_CODE_PREFIX + CodeUtils.digits32(upperCommodityUnitPriceAndPic.getId(), Constants.CODE_NUM));
                            if (upperCommodityUnitPriceAndPic.getGoods() != null) {
                                upperCommodityResponse.setGoodsId(upperCommodityUnitPriceAndPic.getGoods().getId());
                            }
                            upperCommodityResponse.setUnitName(commodity.getUnitName());
                            upperCommodityResponse.setPriceType(commodity.getPriceType());
                            upperCommodityResponse.setStatus(commodity.getStatus());
                            upperCommodityResponse.setCustomerCategoryName(commodity.getCustomerCategory().getName());
                            if (commodity.getBrand() != null) {
                                upperCommodityResponse.setBrandName(commodity.getBrand().getName());
                            }

                            //设置商品默认价格
                            Map<String, Double> unitPrice = upperCommodityUnitPriceAndPic.getUnitPrice();
                            if (unitPrice != null && unitPrice.size() > 0) {
                                upperCommodityResponse.setMin(Collections.min(unitPrice.values()));
                                upperCommodityResponse.setMax(Collections.max(unitPrice.values()));
                                upperCommodityResponse.setUnitPrice(unitPrice);
                            }

                            //商品属性
                            List<CommodityGoodsAttribute> attributeAndValueList = upperCommodityUnitPriceAndPic.getAttributeAndValueList();
                            String attribute = StringUtils.join(attributeAndValueList.stream().sorted(Comparator.comparing(CommodityGoodsAttribute::getId).reversed()).map(commodityGoodsAttribute -> commodityGoodsAttribute.getCustomerAttributeValue().getValue()).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR);
                            upperCommodityResponse.setAttribute(attribute);
                            upperCommodityResponse.setName(commodity.getName());
                            upperCommodityResponse.setApplyTime(commodity.getApplyTime());
                            upperCommodityResponse.setIsMemberPrice(commodity.getIsMemberPrice());
                            upperCommodityResponse.setStatus(commodity.getStatus());
                            upperCommodityResponse.setMemberId(commodity.getMemberId());
                            upperCommodityResponse.setMemberName(commodity.getMemberName());
                            upperCommodityResponse.setMemberRoleId(commodity.getMemberRoleId());
                            upperCommodityResponse.setMemberRoleName(commodity.getMemberRoleName());
                            upperCommodityResponse.setMainPic(commodity.getMainPic());
                            upperCommodityResponse.setMinOrder(commodity.getMinOrder());
                            upperCommodityResponse.setTaxRate(commodity.getTaxRate());

                            Integer type = commodity.getType();
                            upperCommodityResponse.setType(type);
                            LogisticsResponse logisticsResponse = new LogisticsResponse();
                            BeanUtil.copyProperties(commodity.getLogistics(), logisticsResponse);
                            upperCommodityResponse.setLogistics(logisticsResponse);

                            upperCommodityResponse.setSubCommoditySkuId(commodityUnitPriceAndPic.getId());
                            upperCommodityResponseList.add(upperCommodityResponse);
                        }
                    }
                }
            }
        }
        return upperCommodityResponseList;
    }

    /**
     * 校验是否开启Mro模式
     *
     * @param openMroInnerDTO
     * @return
     */
    @Override
    public Boolean checkIsOpenMro(OpenMroInnerDTO openMroInnerDTO) {
        Wrapper<Boolean> wrapper = pageTemplateWebControllerFeign.openMroInner(openMroInnerDTO);
        if (wrapper.getCode() == ResponseCode.SUCCESS.getCode()) {
            return wrapper.getData();
        }
        throw new BusinessException(wrapper.getMessage());
    }

    /**
     * 导出商品sku纬度数据
     */
    @Override
    public void exportCommoditySkuByCommodityIdList(HttpServletResponse response, List<Long> commodityIdList) {
        List<Commodity> commodityList = commodityRepository.findAllById(commodityIdList);
        List<Map<String, Object>> rowList = new ArrayList<>();
        commodityList.forEach(commodity -> {
            List<CommodityUnitPriceAndPic> unitPriceAndPicList = commodity.getUnitPriceAndPicList();
            unitPriceAndPicList.forEach(commodityUnitPriceAndPic -> {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put(CommodityTableEnum.Name.getMessage(), commodity.getName());
                map.put(CommodityTableEnum.Code.getMessage(), commodity.getCode());
                map.put(CommodityTableEnum.Brand.getMessage(), commodity.getBrand() != null ? commodity.getBrand().getName() : "");
                map.put(CommodityTableEnum.CustomerCategory.getMessage(), commodity.getCustomerCategory().getName());
                map.put(CommodityTableEnum.Category.getMessage(), commodity.getCustomerCategory().getCategory() != null ? commodity.getCustomerCategory().getCategory().getName() : "");
                map.put(CommodityTableEnum.Slogan.getMessage(), commodity.getSlogan());
                map.put(CommodityTableEnum.SellingPoint.getMessage(), ArrayUtil.join(commodity.getSellingPoint(), "-"));
                map.put(CommodityTableEnum.CommodityArea.getMessage(), commodity.getCommodityAreaList() != null ? ArrayUtil.join(commodity.getCommodityAreaList().stream().map(commodityArea -> commodityArea.getProvinceName() + "-" + commodityArea.getCityName() + "-" + commodityArea.getRegionName()).toArray(), ";") : "");
                map.put(CommodityTableEnum.UnitName.getMessage(), commodity.getUnitName());
                map.put(CommodityTableEnum.SubUnitName.getMessage(), commodity.getSubUnitName());
                map.put(CommodityTableEnum.MinOrder.getMessage(), commodity.getMinOrder());
                map.put(CommodityTableEnum.PriceType.getMessage(), PriceTypeEnum.getNameByCode(commodity.getPriceType()));
                map.put(CommodityTableEnum.IsMemberPrice.getMessage(), commodity.getIsMemberPrice());
                map.put(CommodityTableEnum.TaxRate.getMessage(), commodity.getTaxRate());

                List<CommodityGoodsAttribute> attributeAndValueList = commodityUnitPriceAndPic.getAttributeAndValueList();
                String attribute = attributeAndValueList != null ? StringUtils.join(attributeAndValueList.stream().sorted(Comparator.comparing(CommodityGoodsAttribute::getId).reversed()).map(commodityGoodsAttribute -> commodityGoodsAttribute.getCustomerAttributeValue() != null ? commodityGoodsAttribute.getCustomerAttributeValue().getValue() : "").filter(Objects::nonNull).toArray(String[]::new), Constants.COMMODITY_NAME_SPLIT_STR) : "";
                map.put(CommodityTableEnum.Attribute.getMessage(), attribute);
                map.put(CommodityTableEnum.Price.getMessage(), MapUtil.sortJoin(commodityUnitPriceAndPic.getUnitPrice(), ";", ":", true));
                map.put(CommodityTableEnum.PriceRate.getMessage(), commodityUnitPriceAndPic.getPriceRate());
                rowList.add(map);
            });
        });

        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getBigWriter();
        CellStyle style = writer.getHeadCellStyle();
        style.setWrapText(true);
        writer.write(rowList);

        String fileName = "commodity-" + DateUtil.formatDate(new Date()) + ".xls";
        try (ServletOutputStream out = response.getOutputStream()) {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }

    /**
     * 根据平台品类id查询商品
     *
     * @param categoryIdList
     * @return
     */
    @Override
    public List<Commodity> findAllByCategoryIdIn(List<Long> categoryIdList) {
        return commodityRepository.findAll((Specification<Commodity>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();
            if (CollectionUtil.isNotEmpty(categoryIdList)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root
                        .join("customerCategory", JoinType.LEFT)
                        .join("category", JoinType.LEFT)
                        .get("id"))
                        .value(categoryIdList));
            }
            return query.distinct(true).where(finalConditions).getRestriction();
        });
    }


    @Override
    public List<Commodity> findAllByCategoryIdInAndAttributeIdIn(List<Long> categoryIdList, List<Long> attributeIdList) {
        return commodityRepository.findAll((Specification<Commodity>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();
            if (CollectionUtil.isNotEmpty(categoryIdList)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root
                        .join("customerCategory", JoinType.LEFT)
                        .join("category", JoinType.LEFT)
                        .get("id"))
                        .value(categoryIdList));
                if (CollectionUtil.isNotEmpty(attributeIdList)) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root
                            .join("customerCategory", JoinType.LEFT)
                            .join("category", JoinType.LEFT)
                            .join("attributeList")
                            .get("id"))
                            .value(attributeIdList));
                }
            }
            return query.distinct(true).where(finalConditions).getRestriction();
        });
    }
}

